【发布时间】:2018-05-19 11:04:48
【问题描述】:
将为您提供输入 I 的文件路径、输出 O 的文件路径、字符串 S 和字符串 T。
读取 I 的内容,将每次出现的 S 替换为 T,并将结果信息写入文件 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)
这是我不断收到的错误:
Traceback(最近一次调用最后一次): 文件“write-text-file.py”,第 15 行,在 file2.replace(S, T) AttributeError: '_io.TextIOWrapper' 对象没有属性 'replace'
【问题讨论】:
-
错误信息非常清楚。你有什么问题?
-
我想我对它说它没有“替换”属性感到困惑,这是否告诉我这是我正在尝试做的错误命令?
-
open 返回一个文件对象...不是字符串。阅读文档:docs.python.org/3.6/tutorial/inputoutput.html
-
您需要对 string 对象而不是文件指针执行
.replace()。因此,您需要先从file2检索内容。提示:read()、readlines()等
标签: python string file replace