将为您提供输入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)
这是我一直得到的错误:
追踪(最近一次通话): 文件“write-text-file.py”,第15行,in file2.replace(S,T) AttributeError:'_ io.TextIOWrapper'对象没有属性'replace'
答案 0 :(得分:0)
# 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)
答案 1 :(得分:0)
file2
是文件对象而不是字符串,文件对象没有替换方法
试
with open(I, 'r') as file1, open(O, 'w') as file2:
for line in file1.readlines():
line=line.replace(S,T)
file2.write(line)