2 回答

TA貢獻(xiàn)2036條經(jīng)驗 獲得超8個贊
我理解你的問題,看起來你想編輯你的 hello.text 文件,并且 .txt 包含一些字符('d)并且你想用任何字符串替換它。所以你可以做這樣的事情,
# Read in the file
with open('hello.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('d', 'abcd')
# Write the file out again
with open('hello.txt', 'w') as file:
file.write(filedata)

TA貢獻(xiàn)1943條經(jīng)驗 獲得超7個贊
就這樣吧。(嘗試?yán)斫馕易隽耸裁?- 這很容易 - 如果你沒有得到任何結(jié)果,請發(fā)表評論..)
def main():
with open("test.txt", "r") as f:
fileData = f.read()
print(fileData)
a = [char for char in fileData]
for i in range(len(a)):
if a[i] == 'd':
a[i] = 'LoL'
else:
continue
with open("test.txt", "w") as f:
f.write(''.join(a))
if __name__=="__main__":
main()
添加回答
舉報