在嵌套for循环中修改文件

2024-09-27 09:26:41 发布

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

我正在迭代其中的目录和文件,同时就地修改每个文件。我期待着有新修改的文件被读取后的权利。 以下是我的代码和描述性注释:

# go through each directory based on their ids
for id in id_list:
    id_dir = os.path.join(ouput_dir, id)
    os.chdir(id_dir)

    # go through all files (with a specific extension)
    for filename in glob('*' + ext):

        # modify the file by replacing all new-line characters with an empty space
        with fileinput.FileInput(filename, inplace=True) as f:
            for line in f:
                print(line.replace('\n', ' '), end='')

        # here I would like to read the NEW modified file
        with open(filename) as newf:
            content = newf.read()

从目前的情况来看,newf不是新修改的,而是原来的f。我想我明白这是为什么,但是我发现很难克服这个问题。你知道吗

我总是可以进行两次独立的迭代(根据每个目录的id,遍历所有文件(具有特定扩展名)并修改文件,然后重复迭代来读取每个文件),但是我希望是否有更有效的方法来解决这个问题。也许,如果有可能在修改发生之后重新启动第二个for循环,然后使read发生(这样至少可以避免重复外部for循环)。你知道吗

有什么想法/设计能以干净高效的方式实现上述目标?你知道吗


Tags: 文件in目录idgoforreados
2条回答

我并不是说你这样做的方式是不正确的,但我觉得你把它复杂化了。这是我的超级简单的解决方案。你知道吗

import glob, fileinput
for filename in glob('*' + ext):

    f_in = (x.rstrip() for x in open(filename, 'rb').readlines()) #instead of trying to modify in place we instead read in data and replace raw_values.
    with open(filename, 'wb') as f_out: # we then write the data stream back out     
    #extra modification to the data can go here, i just remove the /r and /n and write back out
        for i in f_in:
            f_out.write(i)

    #now there is no need to read the data back in because we already have a static referance to it.

对我来说,它适用于以下代码:

#!/usr/bin/env python3
import os
from glob import glob
import fileinput

id_list=['1']
ouput_dir='.'
ext = '.txt'
# go through each directory based on their ids
for id in id_list:
    id_dir = os.path.join(ouput_dir, id)
    os.chdir(id_dir)

    # go through all files (with a specific extension)
    for filename in glob('*' + ext):

        # modify the file by replacing all new-line characters with an empty space
        for line in  fileinput.FileInput(filename, inplace=True):
            print(line.replace('\n', ' ') , end="")

        # here I would like to read the NEW modified file
        with open(filename) as newf:
            content = newf.read()
        print(content)

注意我是如何迭代这些行的!你知道吗

相关问题 更多 >

    热门问题