首页 > 解决方案 > 读取多个文本文件,搜索几个字符串,用 python 替换和写入

问题描述

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

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

#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.xfilejupyter-notebookfile-writingfile-read

解决方案


如果你使用 Pyhton 3,你可以使用scandirin os 库。
Python 3 文档: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 文档:os.listdir

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


推荐阅读