【发布时间】:2017-01-16 09:12:06
【问题描述】:
有 1000 多个 html 文件。
我想做:
- 读取文件。
- 修剪特定行。
- 覆盖文件(不追加)。
以下代码有效。但我认为两次使用“开放”是浪费。我可以写得更简单吗?
for file_path in glob.glob(os.path.join(dir, '*.html')):
with open(file_path, "r", encoding="utf-8") as reader:
html_ = reader.read()
replaced = html_.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "")
with open(file_path, "w", encoding="utf-8") as writer:
writer.write(replaced)
我试过了:
-
'r+':这是加法。 -
'w+':read()方法返回''。
【问题讨论】:
标签: python file python-3.x file-io