我正在逐行读取一个文件,让我说我不关心任何事情,除了"如果"该文件的这一行包含一个大写字母.因为如果它,我想使用它.如果没有,我不想使用文件的这一行.
我可以只使用一个if语句吗?或者我必须使用for循环.我已经有两个嵌套语句.
我的代码:
with open(var) as config_file: #open file
for line in config_file: #line by line reading of file
#if "description" and capital letter is contain in line:
line = line.replace('\n' , '').replace('"' , '').replace(']' , '') #removes all extra characters
i = "| except " + (line.split("description ", 1)[1]) + " " #split the line and save last index (cust name)
cus_str+=i #append to string
config_file.close()
Run Code Online (Sandbox Code Playgroud)
是.内置any函数使这很简单:
with open(filename) as f:
for line in f:
if any(letter.isupper() for letter in line):
print(line)
Run Code Online (Sandbox Code Playgroud)