【问题标题】:Read multiple text files, search few strings , replace and write in python读取多个文本文件,搜索几个字符串,用 python 替换和写入
【发布时间】:2020-09-12 00:05:08
【问题描述】:

我的本​​地目录中有 10 个文本文件,命名为 test1test2test3 等。我想读取所有这些文件,在文件中搜索几个字符串,用其他字符串替换它们,最后以 newtest1newtest2 之类的方式保存回我的目录em>、newtest3 等等。

例如,如果只有一个文件,我会执行以下操作:

#Read the file
with open('H:\\Yugeen\\TestFiles\\test1.txt', 'r') as file :
filedata = file.read()

#Replace the target string
filedata = filedata.replace('32-83 Days', '32-60 Days')

#write the file out again
with open('H:\\Yugeen\\TestFiles\\newtest1.txt', 'w') as file:
file.write(filedata)

有没有什么方法可以在 python 中实现这一点?

【问题讨论】:

    标签: python-3.x file jupyter-notebook file-writing file-read


    【解决方案1】:

    如果你使用 Pyhton 3,你可以使用 os 库中的scandir
    Python 3 docs: os.scandir

    通过它您可以获得目录条目。
    with os.scandir('H:\\Yugeen\\TestFiles') as it:
    然后遍历这些条目,您的代码可能看起来像这样。
    请注意,我将您代码中的路径更改为入口对象路径。

    import os
    
    # Get the directory entries
    with os.scandir('H:\\Yugeen\\TestFiles') as it:
        # Iterate over directory entries
        for entry in it:
            # If not file continue to next iteration
            # This is no need if you are 100% sure there is only files in the directory
            if not entry.is_file():
                continue
    
            # Read the file
            with open(entry.path, 'r') as file:
                filedata = file.read()
    
            # Replace the target string
            filedata = filedata.replace('32-83 Days', '32-60 Days')
    
            # write the file out again
            with open(entry.path, 'w') as file:
                file.write(filedata)
    

    如果你使用 Pyhton 2,你可以使用 listdir。 (也适用于python 3)
    Python 2 docs: os.listdir

    在这种情况下,相同的代码结构。但是您还需要处理文件的完整路径,因为 listdir 只会返回文件名。

    【讨论】:

    • 它没有像我预期的那样保存我的文件,但是,这是一个很好的答案。谢谢。
    猜你喜欢
    • 2016-04-26
    • 2010-10-13
    • 1970-01-01
    • 2020-05-12
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多