微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

读取多个文本文件,搜索几个字符串,替换并用python编写

如何解决读取多个文本文件,搜索几个字符串,替换并用python编写

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

解决方法

如果您使用Pyhton 3,则可以在操作系统库中使用scandir
Typescript compiler is forgetting to add file extensions to ES6 module imports?

这样您就可以获取目录条目。
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 3 docs: os.scandir

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。