【问题标题】:Writing the results of a search from a for loop to a file only give one line (one result)将搜索结果从 for 循环写入文件仅给出一行(一个结果)
【发布时间】:2011-05-03 16:48:33
【问题描述】:

我不明白为什么我只在一个循环中写入的日志文件中获得 word 和 ln 的第一个匹配项(有 50 个或更多匹配项)。而且它的结构不像我打印到屏幕时那样。下面是代码。谢谢!

我正在编写的文件中的结果:343438363939 70642

regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
    for file in files:
        if file.endswith(".log") or file.endswith(".txt"):
            f = open(os.path.join(root,file))
                for i, line in enumerate(f.readlines()):
                    searchedstr = regex.findall(line)
                    ln = str(i)
                    for word in searchedstr:
                         print "\nString found: " + word
                         print "Line: " + ln
                         print "File: " + os.path.join(root,file)
                         print " "
                         logfile = open('result3.log', 'w')
                         logfile.write(word + '\n' + ln)
                         logfile.close()
            f.close()

【问题讨论】:

    标签: python loops writing


    【解决方案1】:

    这是你的问题:

                     logfile = open('result3.log', 'w')
                     logfile.write(word + '\n' + ln)
                     logfile.close()
    

    每次您像这样打开日志文件时,它都会删除之前的所有内容,并且 从文件的开头开始写入。您可以将open 更改为

                     logfile = open('result3.log', 'a')
    

    ('a' 代表 'append'),或者 -- 更好 -- 在最外层循环之外只打开一次 logfile,如下所示:

    regex = re.compile(r'(?:3\d){6}')
    with open('result3.log', 'w') as logfile:
        for root, dirname, files in os.walk(directory):
            # ...
            logfile.write(word + '\n' + ln)
    

    with 负责为您关闭文件,因此您不需要显式的logfile.close()。 (使用with 打开f 会更好,如果f.close() 不在嵌套循环下方悬空。)(进一步附录:enumerate(f.readlines()) 与@ 相同987654332@ 除了更慢。)

    【讨论】:

    • 我做了你提到的更改,它有效,但不可读。所以,我尝试了:logfile.write('\nString:' + word + '\nLine:' + ln + '\n')。它可以工作,但是读取文件的循环似乎永远不会停止。当我尝试删除创建的文件时,它说文件仍然打开,而事实上,它不是。有什么想法吗?
    • 我需要查看完整的程序。请为此提出一个新问题。
    【解决方案2】:

    每次写入时都会覆盖输出文件,因为您使用 'w' 而不是 'a' 打开它以进行追加。

    也许你应该在循环之外打开它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多