繁体   English   中英

替换文件中的文本,Python

[英]replacing text in a file, 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)))

我收到错误消息TypeError:replace()至少接受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

replace是'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()

尝试这个:

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]上调用它。

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

您需要将其称为test_lines[0].replace(test_lines[0],str(content))

在解释器中调用help(str.replace)

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

返回S的副本,其中所有出现的子字符串old都替换为new。 如果给出了可选的参数count,则仅替换第一个出现的计数。

找不到文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM