写入文件循环问题

2024-04-26 22:49:43 发布

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

我遇到的问题是,不是将读取文件的所有行都重写到输出中,而是只有最后一行在输出文件中。我相信它被一遍又一遍地写,但我似乎不知道如何修复这个循环。如果有人能帮我,我将不胜感激。这个问题可能与在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')

Tags: and文件pathinimportretxtfor
1条回答
网友
1楼 · 发布于 2024-04-26 22:49:43

通过将fo = open('outputFile', '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()

相关问题 更多 >