在Python中用文件中的另一个字符串替换字符串

时间:2017-12-05 17:36:26

标签: python string file replace

将为您提供输入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'

2 个答案:

答案 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)