简体   繁体   English

如何用另一条线替换一条线?

[英]How to replace a line with another line?

I am trying to make a contact book application with command-line arguments.我正在尝试使用命令行 arguments 制作通讯录应用程序。 This is the code written so far to update the new contact details of a particular contact.这是迄今为止为更新特定联系人的新联系人详细信息而编写的代码。 args.name has the name of the contact. args.name包含联系人的姓名。 And args.number has the new number which needs to be updated.并且args.number有需要更新的新号码。

How can I update the entire line?如何更新整行? When I run this, it replaces the entire file, contacts.txt , with an empty string.当我运行它时,它会将整个文件contacts.txt替换为一个空字符串。 This functionality will also help in the delete function.此功能还有助于删除 function。

thefile = open("contacts.txt","w+")
lines = thefile.readlines()
for line in lines:
     if name in line:
           line.replace(line,"Name: "+ args.name + " Number: "+args.number+ "\n")

You could firstly read the data from the file, create an empty string, append each line to the newly created string conditionally, and write(replace) the newly obtained string onto the existing file.您可以先从文件中读取数据,创建一个空字符串,append 每行有条件地写入新创建的字符串,并将新获得的字符串写入(替换)到现有文件中。

f1 = open('contacts.txt','r')

data = f1.readlines()
f1.close()
new_data = ""

for line in data:
   if name in line:
     update = line.replace(line,"Name: "+ args.name + " Number: "+args.number+ "\n")
     new_data += update
   else:
     new_data += line

f2 = open('contacts.txt','w')
f2.write(new_data)
f2.close()

When you open a file with "w+" python erase the file: First you whoud write two function: One that writes data and the other read data当你用 "w+" python 打开一个文件时擦除文件:首先你要写两个函数:一个写数据,另一个读数据

def reader():
    f = open("MYFILE.txt", "r")
    lines = f.readlines()
    f.close()
    return lines

def writer(data):
    f = open("MYFILE.txt", "w")
    for i in data:
        f.write(i)
    f.close()

Then you can actualise lines how you want:然后你可以实现你想要的线条:

lines = reader()

for i in range(len(lines)):
    if lines[i] == "Something\n":
        lines[i] = "New_Value\n"
writer(lines)

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

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