检查文件中的行是否包含Python中的大写字母

2024-05-17 13:00:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在逐行阅读一个文件,假设除了“如果”文件的这一行包含一个大写字母,我什么都不关心。因为如果是的话,我想用它。我不想使用文件的此行,如果它没有。在

我可以用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()

Tags: and文件inconfigforiflinedescription
3条回答
with open(var) as config_file :
    data = [i.strip() for i in config_file.readlines() if any(j != j.lower() for j in i)]

data将只包含大写字符的字符串。在

是的。内置的^{}函数使这一点变得简单:

with open(filename) as f:
    for line in f:
        if any(letter.isupper() for letter in line):
            print(line)

正则表达式对此可能有点过头了,但它非常简单:

import re
if re.search('[A-Z]', line):

相关问题 更多 >