I want to add the file extensions found in the function to the line of code where I specified “HERE”. In other words, not only “.txt”, but also the extensions of the above function should be brought that part. In short, I want to associate the following code with the function.
Can you help me, with this?
JavaScript
x
37
37
1
def extention_finder(file_path):
2
3
if ".XLSX" in file_path.upper():
4
ext = ".xlsx"
5
elif ".XLS" in file_path.upper():
6
ext = ".xls"
7
elif ".TXT" in file_path.upper():
8
ext = ".txt"
9
elif ".CSV" in file_path.upper():
10
ext = ".csv"
11
elif ".XLT" in file_path.upper():
12
ext = ".xlt"
13
elif ".zip" in file_path.upper():
14
ext = ".zip"
15
else:
16
ext = "N/A"
17
18
19
20
counts = 1
21
myZip = zipfile.ZipFile(path_to_zip_file)
22
print(myZip.namelist())
23
24
for file in myZip.filelist:
25
if file.filename.endswith(".txt"): # HERE HERE HERE HERE HERE HERE
26
if os.path.basename(file.filename) in os.listdir(directory_to_extract_to):
27
source = myZip.open(file)
28
target = open(os.path.join(directory_to_extract_to, os.path.basename(file.filename).split(".")[0] + "_" + str(counts) + "." + os.path.basename(file.filename).split(".")[1]), "wb")
29
counts = counts + 1
30
31
else:
32
source = myZip.open(file)
33
target = open(os.path.join(directory_to_extract_to, os.path.basename(file.filename)), "wb")
34
35
with source, target:
36
shutil.copyfileobj(source, target)
37
Advertisement
Answer
Assuming that the only .
in the string file_path
is the one that starts the file extension, this rewrite of your function should do the job:
JavaScript
1
4
1
def extension_finder(file_path):
2
paths = ["XLSX", "XLS", "TXT", "CSV", "XLT", "ZIP"]
3
return file_path.split(".")[1].upper() in paths
4
Then in the if statement you can call extension_finder
with the path you want to check.