[英]Replace a string with another string within a file in Python
將為您提供輸入I的文件路徑,輸出O的文件路徑,字符串S和字符串T。
讀取I的內容,用T替換每次出現的S並將結果信息寫入文件O。
如果O已經存在,則應將其替換。
# Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]
# Your code goes here
# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
file2.replace(S, T)
file1.close()
file2.close()
file2= open('O', 'r')
print(file2)
這是我不斷得到的錯誤:
追溯(最近一次通話最近):file2.replace(S,T)中的文件“ write-text-file.py”,第15行,AttributeError:'_io.TextIOWrapper'對象沒有屬性'replace'
# Get the filepath from the command line
import sys
import re
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]
# Your code goes here
# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)
file1.close()
file2.close()
file2= open(O, 'r')
data = file2.read()
print(data)
file2
是文件對象,不是字符串,文件對象沒有replace方法
嘗試
with open(I, 'r') as file1, open(O, 'w') as file2:
for line in file1.readlines():
line=line.replace(S,T)
file2.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.