【发布时间】:2020-08-19 00:08:25
【问题描述】:
我有很多文本文件
我想改变他们的第一个词我试过这个,但没有奏效。 我想阅读所有文本文件,打开它们并将第一个单词(8 个字符)更改为一个相同的短语
import os
for filename in os.listdir("data"):
if filename.endswith(".txt"):
content = filename.read()
with open(os.path.join("data" , filename) , "w") as outfile:
outfile.write("new word" + content[8:])
错误:
Traceback (most recent call last): File "change.py", line 5, in <module> content = filename.read() AttributeError: 'str' object has no attribute 'read'
【问题讨论】:
-
有问题吗?请参阅How to Ask、help center。
-
这里目前没有问题。我猜这会导致异常。例外是告诉你出了什么问题。它说的应该是可以理解的,但如果不是,那么你可以问你不明白的地方。
标签: python file-handling