IT-Swarm.Net

在蟒蛇中编辑文本文件中的特定行

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

Dan
Warrior
500
1
0

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

#!/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()

是的,我知道myfile.writelines('Mage')[1]是不正确的。但是你明白了我的观点吧?我正在尝试用Mage替换Warrior来编辑第2行。但我甚至可以这样做吗?

57
nn2

你想做这样的事情:

# 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 )

原因是你不能直接在文件中执行“更改第2行”之类的操作。您只能覆盖(而不是删除)文件的某些部分 - 这意味着新内容仅涵盖旧内容。所以,如果你在第2行写“Mage”,那么结果就是'Mageior'。.

77
Jochen Ritzel

快速,可靠且价格合理的云托管

注册并在30天内获得$50奖金!

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

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line
17
ghostdog74
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()

然后:

replace_line('stats.txt', 0, 'Mage')
15
Peter C

如果您的文字只包含一个人:

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()

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

进口重新

# 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()

如果个人的“工作”在短信中具有恒定的长度,则您可以仅更改与所需个人的“工作”相对应的文本部分:这与发送者的一个相同。.

但根据我的说法,更好的方法是将个人的特征放在用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
2
eyquem

您可以通过两种方式完成,选择适合您需求的方式:

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

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

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

二,写入文件(其中 枚举 来行动)

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)

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

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

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.  

“战士”已被“法师”取代,因此请将更新的数据写入文件:

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

这是 输出 将在两种情况下:

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

我今天晚上一直在练习文件,并意识到我可以建立在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))
1
theYnot