问题描述
我想更改他们的第一个单词,我尝试了此操作,但没有成功。 我想阅读所有文本文件,打开它们,然后将第一个单词(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'
解决方法
根据对您问题的理解,我提出了此解决方案。请让我知道这是否不是您想要的解决方案。
import os
def fread(file):
with open(file,"r") as f:
lines = f.readlines()
f.close()
return lines
def replace(file,folder):
lines = fread(file)
with open(file,'w') as four:
for x in lines:
print(x[0])
s = x[0] # first word with n characters
fout.write(x.replace(s,'your desired replacement'))
fout.close()
if __name__ == "__main__":
folder = "your folder containing files"
curretndir = os.getcwd()
os.chdir(folder)
for files in os.listdir(folder):
if files.endswith(".txt"):
replace(files,folder)
如果我知道文件的内容,那就太好了。根据需要,您必须使用.split()函数。我假设您的内容采用以下形式: word1 word2 word3 ... \ n wordn wordn + 1 .... \ n
,我已标记您的错误。
import os
for filename in os.listdir("data"):
if filename.endswith(".txt"):
with open(os.path.join("data",filename),"r") as f: #<<-- you forgot to open the file like this
content = f.read()
with open(os.path.join("data","r") as outfile: #<<-- you are trying to read the file by using "r" change this to "w"
outfile.write("new word" + content[8:]) #<<-- you are writing to the file
,
import os
for filename in os.listdir("data"):
if filename.endswith(".txt"):
with open(os.path.join("data","r") as f:
content = f.read()
with open(os.path.join("data","w") as outfile:
outfile.write("new word" + content[8:])