[英]How to write "If file type is NOT txt or csv, do X" inside for loop?
我有一個包含三種文件類型(文本、csv 和子目錄)的目錄。 我編寫了一個要應用於文本文件的腳本版本,以及一個要應用於 for 循環內的 csv 文件的修改版本。 隨后,我想忽略子目錄以及我可能擁有的任何其他文件類型。
我知道我可以執行以下操作...
for file in glob.glob('*'):
if file.endswith ('.txt'):
# run script1 here
elif file.endswith ('.csv'):
# run script2 here
else:
continue
但是由於腳本很長,我想在腳本的開頭將“else”語句反轉為“if not”語句 - 如果只是為了提高可讀性。 我知道我可以使用其中一種文件類型(在這種情況下為 .txt)來做到這一點。...
for file in glob.glob('*'):
if not file.endswith ('.txt'):
continue
else:
# run script1 here
但是我怎樣才能改變腳本,以便我問“如果文件不是txt 或 csv 做 X,如果文件是txt 做 Y,如果文件是csv 到 Z”。 我懷疑這是一個簡單的修復,但我無法解決。 這是我之前進行的一次嘗試,但會產生錯誤...
for file in glob.glob('*'):
if not file.endswith ('.txt') or ('.csv'):
continue
elif file.endswith ('.txt'):
# run script1 here
else:
# run script2 here
每個布爾表達式都是單獨計算的。
not file.endswith ('.txt') or ('.csv')
評估為真:非空元組被視為真值。
for file in glob.glob('*'):
if not file.endswith ('.txt') or not file.endswith ('.csv'):
continue
elif file.endswith ('.txt'):
# run script1 here
else:
# run script2 here
or
結合兩個表達式; 它不是一個單一的布爾表達式的一部分。
if not (file.endswith('.txt') or file.endswith('.csv')):
但是, endswith
本身可以采用字符串元組:
if not file.endswith(('.txt', '.csv')):
在您的第三個代碼片段中,您必須再次調用.endswith()
,如下所示:
for file in glob.glob('*'):
if not file.endswith ('.txt') or file.endswith('.csv'):
continue
elif file.endswith ('.txt'):
# run script1 here
else:
# run script2 here
這應該工作
既然你是無論如何通配符的文件,為什么不僅glob
你真正想要的文件?
然后你可以寫得更簡潔:
from glob import glob
for file in glob("*.txt") + glob("*.csv"):
if file.endswith(".txt"):
print("run script 1")
else:
print("run script 2")
甚至比這更好(IMO):
from glob import glob
for file in glob("*.txt"):
print("run script 1")
for file in glob("*.csv"):
print("run script 2")
由於文件名有“.txt”或“.csv”,我認為,您將通過僅使用 if 語句獲得您想要的結果,並且您不需要else:continue
子句,因為如果文件名沒有任何這些,如果條件將失敗,什么也不會發生。
for file in glob.glob('*'):
if file.endwith('.txt'):
#do something
if file.endwith('.csv'):
#do something
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.