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/

相关文章:

python - PyTorch 尝试第二次向后浏览图表时出错

python - OS X 10.6.3/Python 2.6.1 上的应用程序脚本

java - 我不断收到此 "Syntax error on token "(", ; expected after this token"错误?

r - 为什么这个 for 循环会出现 46 个错误?

JavaScript 函数在某个 if 语句后停止

javascript - 在存储多种数据类型的项目时访问数组元素的恒定时间

python - pycuda 失败; Theano 与 Anaconda

python - 背景中的多种颜色(过渡)

linux - 如何在 bash 脚本中反转 for 循环

java - 带有改变大小的数组列表的双 for 循环