[英]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.