在 Python 中编辑文本文件中的特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4719438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:11:14  来源:igfitidea点击:

Editing specific line in text file in Python

pythonio

提问by test

Let's say I have a text file containing:

假设我有一个包含以下内容的文本文件:

Dan
Warrior
500
1
0

Is there a way I can edit a specific line in that text file? Right now I have this:

有没有办法可以编辑该文本文件中的特定行?现在我有这个:

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]

try:
    myfile = open('stats.txt', 'a')
    myfile.writelines('Mage')[1]
except IOError:
        myfile.close()
finally:
        myfile.close()

Yes, I know that myfile.writelines('Mage')[1]is incorrect. But you get my point, right? I'm trying to edit line 2 by replacing Warrior with Mage. But can I even do that?

是的,我知道这myfile.writelines('Mage')[1]是不正确的。但你明白我的意思,对吗?我正在尝试通过将 Warrior 替换为 Mage 来编辑第 2 行。但我能做到吗?

采纳答案by Jochen Ritzel

You want to do something like this:

你想做这样的事情:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

这样做的原因是您不能直接在文件中执行诸如“更改第 2 行”之类的操作。您只能覆盖(而不是删除)文件的一部分 - 这意味着新内容只会覆盖旧内容。因此,如果您在第 2 行上写了 'Mage',则结果行将是 'Mageior'。

回答by Peter C

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

And then:

进而:

replace_line('stats.txt', 0, 'Mage')

回答by ghostdog74

you can use fileinput to do in place editing

您可以使用 fileinput 进行就地编辑

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line

回答by eyquem

If your text contains only one individual:

如果您的文本仅包含一个人:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If your text contains several individuals:

如果您的文本包含多个人:

import re

进口重新

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim  \n  dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that's the same idea as senderle's one.

如果一个人的“工作”在文本中的长度是恒定的,你只能改变文本中与所需个人“工作”相对应的部分:这与发送者的想法相同。

But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:

但据我所知,最好将个人的特征放在用 cPickle 记录在文件中的字典中:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '\nid_cards after change==',id_cards

回答by Aseem Yadav

You can do it in two ways, choose what suits your requirement:

您可以通过两种方式进行操作,选择适合您要求的方式:

Method I.)Replacing using line number. You can use built-in function enumerate()in this case:

方法 I.)使用行号替换。enumerate()在这种情况下,您可以使用内置函数:

First, in read modeget all data in a variable

首先,在读取模式下获取变量中的所有数据

with open("your_file.txt",'r') as f:
    get_all=f.readlines()

Second, write to the file (where enumeratecomes to action)

其次,写入文件(枚举起作用的地方)

with open("your_file.txt",'w') as f:
    for i,line in enumerate(get_all,1):         ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)    
        if i == 2:                              ## OVERWRITES line:2
            f.writelines("Mage\n")
        else:
            f.writelines(line)

Method II.)Using the keyword you want to replace:

方法 II.)使用要替换的关键字:

Open file in read modeand copy the contents to a list

读取模式打开文件并将内容复制到列表中

with open("some_file.txt","r") as f:
    newline=[]
    for word in f.readlines():        
        newline.append(word.replace("Warrior","Mage"))  ## Replace the keyword while you copy.  

"Warrior" has been replaced by "Mage", so write the updated data to the file:

“Warrior”已被“Mage”取代,因此将更新的数据写入文件:

with open("some_file.txt","w") as f:
    for line in newline:
        f.writelines(line)

This is what the outputwill be in both cases:

这是两种情况下的输出

Dan                   Dan           
Warrior   ------>     Mage       
500                   500           
1                     1   
0                     0           

回答by theYnot

I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

我今晚一直在练习处理文件,并意识到我可以在 Jochen 的答案的基础上为重复/多次使用提供更强大的功能。不幸的是,我的回答没有解决处理大文件的问题,但确实让小文件的生活更轻松。

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))

回答by Shivam Rai

Suppose I have a file named file_nameas following:

假设我有一个名为file_name如下的文件:

this is python
it is file handling
this is editing of line

We have to replace line 2 with "modification is done":

我们必须用“修改完成”替换第 2 行:

f=open("file_name","r+")
a=f.readlines()
for line in f:
   if line.startswith("rai"):
      p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
   o.write(i)
o.close()
#now the modification is done in the file