Skip to main content
 首页 » 编程设计

python之在嵌套的 for 循环中就地修改文件

2024年10月17日7shanyou

我在修改每个文件的同时迭代其中的目录和文件。我希望在之后立即读取新修改的 文件。 这是我的代码和描述性注释:

# 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。我想我明白为什么会这样,但是我发现很难克服这个问题。

我总是可以做 2 次单独的迭代(根据它们的 ID 遍历每个目录,遍历所有文件(具有特定扩展名)并修改文件,然后重复迭代以读取每个文件)但我希望如果有更有效的方法解决它。也许如果可以在修改发生后重新启动第二个for循环,然后进行read(这样可以避免至少重复外部 for 循环)。

有什么想法/设计可以以简洁高效的方式实现上述目标吗?

请您参考如下方法:

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

#!/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) 

注意我是如何遍历这些行的!