所以这段代码是为了从文件中取出一行并用新的单词/数字替换字符串中的某一行,但它似乎不起作用:(替换文件中的文本,Python
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
我得到错误信息类型错误:更换()至少需要2个参数(1给出),我不知道为什么(内容)不被接受作为参数也会发生这种情况下面
的代码。if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
其实我想他想用test_lines替换test_lines中的第一个字符,所以:'test_lines.replace(test_lines [0],str(content))''。但我可能是错的。 – Guy
readlines()返回一个文件的所有行的列表 – jbh
是的,我刚刚注意到。我的错。 – Guy