簡體   English   中英

在 Python 中編輯文本文件中的特定行

[英]Editing specific line in text file in 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]不正確。 但是你明白我的意思,對吧? 我正在嘗試通過用法師替換戰士來編輯第 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 行”之類的操作。 您只能覆蓋(而不是刪除)文件的一部分 - 這意味着新內容只會覆蓋舊內容。 因此,如果您在第 2 行上寫了 'Mage',則結果行將是 'Mageior'。

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

您可以使用 fileinput 進行就地編輯

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

您可以通過兩種方式進行操作,選擇適合您要求的方式:

方法 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.  

“Warrior”已被“Mage”取代,因此將更新的數據寫入文件:

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           

如果您的文本僅包含一個人:

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

我今晚一直在練習處理文件,並意識到我可以在 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))

寫入初始數據,打印一個空str以將其更新為新數據 這里我們在代碼的最后一行插入一個空str ,此代碼可用於交互更新,即在文本.txt文件中附加數據

with open("data.txt", 'w') as f:
    f.write('first line\n'
            'second line\n'
            'third line\n'
            'fourth line\n'
            ' \n')

更新文本文件最后一行的數據

my_file=open('data.txt')
string_list = my_file.readlines()
string_list[-1] = "Edit the list of strings as desired\n"
my_file = open("data.txt", "w")
new_file_contents = "". join(string_list)
my_file. write(new_file_contents)

我曾經有過同樣的要求,最終以 Jinja 模板告終。 將您的文本文件更改為下面的內容和一個變量 lastname,然后您可以通過傳遞lastname='Meg'來呈現模板,這是我能想到的最有效和最快捷的方法。

Dan 
{{ lastname }} 
Warrior 
500 
1 
0

假設我有一個名為file_name的文件,如下所示:

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

我們必須用“修改完成”替換第 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
#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

這是最簡單的方法。

f = open("file.txt", "wt")
for line in f:
    f.write(line.replace('foo', 'bar'))
f.close()

我希望它對你有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM