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

比方说,我有一个文本文件,其中包含:

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]是不正确的。 但你明白我的观点吧? 我试图通过用法师replace战士来编辑第2行。 但我可以这样做吗?

你想要做这样的事情:

 # 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”。 你只能覆盖(而不是删除)文件的一部分 – 这意味着新的内容只是覆盖旧的内容。 所以,如果你在第二行写了“法师”,结果会是“Mageior”。

你可以使用fileinput来进行编辑

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

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

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

如果一个人的“工作”在texte中是一个固定的长度,那么你可以只改变对应于“工作”的texte部分作为所需的个人:这与senderle的一样。

但是根据我的说法,最好的做法是把个人的特征放在cPickle中logging下来的词典中:

 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 

你可以用两种方法来做,select适合你的要求:

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

首先,在读取模式下获取一个variables中的所有数据

 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) 

方法二。)使用你想要replace的关键字:

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

 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 

我今天晚上一直在从事文件的工作,并意识到我可以build立在Jochen的答案上,为重复/多次使用提供更多的function。 不幸的是,我的回答并没有解决处理大文件的问题,但在小文件中使生活更轻松。

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