簡體   English   中英

如何替換文件中的文本?

[英]How to replace a text in file?

基本上我試圖用 B 替換 A,我設法更改第一行,然后其他兩行被刪除並引發錯誤:

replace_txt = replace_txt[search_txt]
TypeError: string indices must be integers

我的文字:

A is best
A is cool
A is awesome

我的代碼:

import fileinput

replace_txt = {'A':'B'}
for line in fileinput.input('text1.txt', inplace=True):
    for search_txt in replace_txt:
        replace_txt = replace_txt[search_txt]
        line = line.replace(search_txt, replace_txt)
    print(line, end='')

這條線

replace_txt = replace_txt[search_txt]

用字符串覆蓋您的查找字典。 所以下一次replace_txt不再是字典,所以選擇使用[ ]會給你一個錯誤。 調用你的查找字典別的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM