在目录中搜索“中止”的文件

2024-10-02 14:25:09 发布

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

我的代码在目录中搜索*.lis文件并搜索aborted-*.lis文件

这是我的密码:

def aborted_files(file):
    in_file = open(file,'r')
    for lines in in_file.readlines():
        if re.search("aborted", lines):
            print in_file

    in_file.close()

for file in os.listdir("./"):
    if file.endswith(".lis"):
        aborted_files(file)

我在两个文件lisfile1.lislisfile2.lis中测试它

lisfile1.lis中,我有aborted,代码的结果是:

<open file 'lisfile1.lis', mode 'r' at 0x2b0edd174660>
<open file 'lisfile1.lis', mode 'r' at 0x2b0edd174660>

你能帮我只得到aborted-*.lis文件名吗。
我的代码中有什么不正确


Tags: 文件代码in目录forifmodefiles
2条回答
  1. 如果要打印文件名,只需打印出file.name变量即可

  2. 然后,这里不需要re.search()函数,只要使用in

  3. 使用return返回文件名比使用print更好

    但是,如果在这里使用print,它将打印文件名n次(n是该文件中的aborted

  4. .readlines()这里也没用

  5. 使用with自动关闭文件会更简单、更安全


def aborted_files(file):
    with open(file, 'r') as in_file:
        for lines in in_file:
            if "aborted" in lines:
                return in_file.name

for file in os.listdir("./"):
    if file.endswith(".lis"):
        print aborted_files(file)

这里有两件事

(1)打印每个匹配的文件。我猜如果>= 1出现'aborted',您可能只想打印一次文件名。 (2) 打印的是实际的文件对象,而不是文件名。另外,您只需使用with open(...),它将为您处理关闭文件的问题

def aborted_files(file):
    with open(file, 'r') as in_file:
        for lines in in_file.readlines():
            if re.search("aborted", lines):
                print in_file.name
                return

相关问题 更多 >