在Python中找到特定行后追加 [英] Appending a specific line after having found it in Python
问题描述
我正在编写一个函数,允许用户在特定行(文件中)中查找内容,并替换该行中的部分内容,然后将其重新写入同一行中的文件中./p>
I am writing a function that allows a user to look for content in a specific line (in a file), and replace part of that content in that line, and re-writes it to the file on the same line.
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
将具有所有信息,包括修改后的电子邮件地址(按相同顺序).
The above code works, i.e. if the user was to edit the player's email address, his input would change the 3rd element in line
, and lineStr
would have all the information including the modified email address in the same order.
我被困在需要将 lineStr
重新写入到文件中的那一行,该行与原始文件相同.该文件看起来像这样
I am stuck at the point where I need to re-write lineStr
into my file on the same line as the original one. The file looks like so
Joe;Bloggs;j.bloggs@anemailaddress.com
Sarah;Brown;s.brown@anemailaddress.com
发生问题是因为在编写时
The problem occurs because when writing
f.write(lineStr)
文件的第一行将被替换,因此如果我要修改Sarah的第二名(到Stack)并将其写到文件中,该文件将类似于
the first line of the file will be replaced, so if I were to modify Sarah's second name (to Stack) and write it to the file, the file would look like
Sarah;Stack;s.brown@anemailaddress.com
Sarah;Brown;s.brown@anemailaddress.com
而不是外观,即:
Joe;Bloggs;j.bloggs@anemailaddress.com
Sarah;Stack;s.brown@anemailaddress.com
有人能引导我朝正确的方向前进吗?任何帮助,将不胜感激.谢谢
Could anyone lead me in the right direction? Any help would be appreciated. Thank you
推荐答案
您需要执行此操作的方法以及大多数程序执行此操作的方法-写入具有正确输出的临时文件,然后替换原始文件.这是最简单的方法.
The way you need to do this, and the way most programs do it - is to write a temporary file with the correct output, then replace the original file. This is the most fool proof way.
这是一般逻辑:
- 打开输入文件和一个临时输出文件.
- 从输入文件中读取一行:
- Open the input file, and a temporary output file.
- Read a line from the input file:
- 如果符合替换条件,则将新修改的行写入临时输出文件;否则,将该行原样写入输出文件.
要在Python中实现它:
To implement it in Python:
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')
这篇关于在Python中找到特定行后追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!