python-3.x - 读取多个文本文件,搜索几个字符串,用 python 替换和写入
问题描述
我的本地目录中有 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 中实现这一点吗?
解决方案
如果你使用 Pyhton 3,你可以使用scandir
in 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 只会返回文件名。
推荐阅读
- firebase - currentUser.displayName 不起作用并在短时间内返回 null
- gatsby - Gatsby markdown-remark-images 未显示
- python - 如何在 Django 网站的 HTML 页面中显示数据库数据?
- java - 使用java在elasticsearch中索引geojson文件
- mongodb - mongoimport 和 mongorestore 无法连接到 CosmosDB 3.6,无法识别 retrywrites 选项
- reactjs - process.env 位于哪里
- react-native - Hashtag formatter 文本输入反应原生
- amazon-web-services - aws ec2 实例 dns 公共名称更改
- python - Pymupdf getTextbox 返回空
- php - npm 问题 laravel popper install