【问题标题】:Modifying a file in-place inside nested for loops在嵌套的 for 循环中就地修改文件
【发布时间】:2016-10-16 17:59:59
【问题描述】:

当我修改每个文件时,我正在迭代其中的目录和文件。我希望在之后立即读取 新修改的 文件。 这是我的带有描述性 cmets 的代码:

# 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 循环) .

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

【问题讨论】:

  • 你只打印被替换的值,你永远不会改变它。 line.replace() 返回一行的新实例并且不会覆盖原来的实例?
  • @TheLazyScripter 我刚刚纠正了一个小错字。除此之外,执行替换的代码块工作正常;即,如果我单独尝试它,它会修改并就地保存文件。
  • 你试过用line = line.replace('\n', ' '); print(line);替换print(line.replace('\n', ' '), end='')吗?
  • 您是否尝试在for line in f: 循环结束时使用f.write()f.close() 保存文件?
  • @JanZeiseweis 不,它不起作用。另外,我不明白额外的print 语句是做什么的。

标签: python python-3.x for-loop in-place


【解决方案1】:

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

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

注意我是如何遍历线条的!

【讨论】:

    【解决方案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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多