Python 3.x 读取多个文本文件,搜索少量字符串,替换并用python编写

Python 3.x 读取多个文本文件,搜索少量字符串,替换并用python编写,python-3.x,file,jupyter-notebook,file-writing,file-read,Python 3.x,File,Jupyter Notebook,File Writing,File Read,我的本地目录中有10个文本文件,它们的名称类似于test1、test2、test3等等。我想读取所有这些文件,搜索文件中的几个字符串,用其他字符串替换它们,最后以某种方式保存回我的目录,比如newtest1、newtest2、newtest3等等 例如,如果只有一个文件,我会执行以下操作: #Read the file with open('H:\\Yugeen\\TestFiles\\test1.txt', 'r') as file : filedata = file.read() #Rep

我的本地目录中有10个文本文件,它们的名称类似于test1、test2、test3等等。我想读取所有这些文件,搜索文件中的几个字符串,用其他字符串替换它们,最后以某种方式保存回我的目录,比如newtest1、newtest2、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中实现这一点吗?

如果使用Pyton 3,可以使用os库中的
scandir

这样您就可以获得目录条目。
与os.scandir('H:\\Yugeen\\TestFiles')一样:

然后在这些条目上循环,您的代码可能看起来像这样。
注意,我将代码中的路径更改为条目对象路径

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)


在本例中,使用相同的代码结构。但是您还需要处理文件的完整路径,因为listdir将只返回文件名。

它没有像我预期的那样保存我的文件,但是,这是一个很好的答案。谢谢