2014-03-02 89 views
0

所以这段代码是为了从文件中取出一行并用新的单词/数字替换字符串中的某一行,但它似乎不起作用:(替换文件中的文本,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 

回答

0

替换为 'STR' 对象的功能。

听起来像是你想要做这样的事情(这是不是知道你输入的猜测)

test_lines[0].replace(test_lines[0],str(content)) 

我不知道你试图用逻辑来实现在那里。看起来像要完全删除该行并将其替换?

还我不能确定你正在尝试与

content = (y) 

做输入输出是STR(这是你想要的)

编辑:

在你的具体情况(更换一整行),我会建议只是在列表中重新分配该项目。例如

test_lines[0] = content 

要覆盖文件,您将不得不截断它以避免任何竞争条件。所以一旦你对记忆做出了改变,你应该寻找开始,并重写所有的东西。

# Your logic for replacing the line or desired changes 
myfile.seek(0) 
for l in test_lines: 
    myfile.write("%s\n" % l) 
myfile.truncate() 
+0

其实我想他想用test_lines替换test_lines中的第一个字符,所以:'test_lines.replace(test_lines [0],str(content))''。但我可能是错的。 – Guy

+0

readlines()返回一个文件的所有行的列表 – jbh

+0

是的,我刚刚注意到。我的错。 – Guy

0

试试这个:

test_lines = myfile.readlines() 
print(test_lines[0]) 
y = input("change name to:") 
content = str(y) 
myfile.write(test_lines[0].replace(test_lines[0], content)) 

你没有纯粹称为str对象。必须在字符串对象上调用方法replace()。你可以在test_lines[0]上调用它来引用一个字符串对象。

但是,您可能需要更改实际的程序流程。但是,这应该规避错误。

0

你需要调用它作为test_lines[0].replace(test_lines[0],str(content))

调用help(str.replace)的解释。

replace(...) S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

找不到文档。