在Python中找到特定行后追加该行
我正在编写一个函数,允许用户查找特定行(文件)中的内容,并替换该行中的部分内容,然后将其重新写入同一行中的文件在Python中找到特定行后追加该行,python,file,writing,Python,File,Writing,我正在编写一个函数,允许用户查找特定行(文件)中的内容,并替换该行中的部分内容,然后将其重新写入同一行中的文件 def editPlayer(): print "What information would you like to edit?" print "1- Forname" print "2- Surname" print "3- Email address" choice = int(raw_input("")) f = open("p
def editPlayer():
print "What information would you like to edit?"
print "1- Forname"
print "2- Surname"
print "3- Email address"
choice = int(raw_input(""))
f = open("persons.txt","r+")
for i in range(2): # number of type of information
if choice == i: #check if choice equal current running of i
line[choice-1] = str(raw_input("Enter new information: ")) #modify choice-1's element in line
lineStr = line[0] + ";" + line[1] + ";" + line[2] #makes list in a string
上述代码起作用,即如果用户要编辑玩家的电子邮件地址,他的输入将更改line
中的第三个元素,并且lineStr
将以相同的顺序包含所有信息,包括修改后的电子邮件地址
我被困在需要将lineStr
重新写入与原始文件位于同一行的文件的位置。文件看起来是这样的
Joe;Bloggs;j.bloggs@anemailaddress.com
Sarah;Brown;s.brown@anemailaddress.com
出现问题的原因是,在编写
f.write(lineStr)
文件的第一行将被替换,因此,如果我修改Sarah的第二个名称(要堆叠)并将其写入文件,该文件将如下所示
Sarah;Stack;s.brown@anemailaddress.com
Sarah;Brown;s.brown@anemailaddress.com
而不是它的外观,即:
Joe;Bloggs;j.bloggs@anemailaddress.com
Sarah;Stack;s.brown@anemailaddress.com
谁能把我引向正确的方向?任何帮助都将不胜感激。谢谢您需要这样做的方式,以及大多数程序都是这样做的——用正确的输出编写一个临时文件,然后替换原始文件。这是最简单的方法 以下是一般逻辑:
import os
with open('input.txt') as i, open('output.txt', 'w') as o:
for line in i:
if line.startswith('Replace Me:'):
line = 'New line, replaced the old line.\n'
o.write(line)
os.rename('output.txt', 'input.txt')
我将使用
csv
模块,请参阅。我同意@Alexe-如果您可以使用csv.DictReader和csv.DictWriter读取和写入数据,您可能会获得更多的控制权。但是您的基本问题已经得到了回答,可以这样做,但不明智