python - 写入文件循环问题

标签 python for-loop

我遇到的问题是,不是将读取文件的所有行写入输出,而是只有最后一行位于输出文件中。我相信它被一遍又一遍地写,但我似乎不知道如何修复循环。如果有人可以帮助我,我将不胜感激。此问题可能是由于在 for 循环中重复打开我的文件所致。

import os
import re

# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\Bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
    fullpath = os.path.join(path, filename)
    if filename=="text.txt":
        # 2.open file. read from file
        fi = open(fullpath, 'r')
        # 3.parse text in incoming file and use regex to find PATH
        for line in fi:
            m = re.search("(Adding file.*)",line)
            if m:
                #4.write path and info to outgoing file
                #print(line)
                fo = open('outputFile', 'w')
                fo.write(line + '\n')

最佳答案

通过将 for = open('output_File', 'w') 放在开头,我得到了所需的结果,并且脚本处理速度更快。

import os
import re
fo = open('outputFile', 'w')
# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\Bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
    fullpath = os.path.join(path, filename)
    if filename=="text.txt":
        # 2.open file. read from file
        fi = open(fullpath, 'r')
        # 3.parse text in incoming file and use regex to find PATH
        for line in fi:
            m = re.search(r'(Adding file.*)',line)
            if m:
                fo.write(line)
fo.close()
fi.close()

关于python - 写入文件循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373607/

相关文章:

r - 如何从 R 中的 for 循环填充矩阵

r - R 中的 For 循环不打印我需要的内容

Python,speech_recognition 工具无法识别 .wav 文件

Python应用跨平台分发

python - 如何使用 matplotlib 在 python 中保存绘图?

Java:根据整数是奇数还是偶数将整数放在双端队列中的第一个或最后一个

javascript - Django MongoEngine CORS 错误

python - 在 python 中使用确定组合不同的长列表

python - 两个 for 循环,第二个仅在第一次迭代时执行 python

c - Visual Studio 在 for 循环后要求分号