programing

Python에서 텍스트 파일의 특정 행 편집

fastcode 2023. 8. 28. 22:23
반응형

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]틀렸습니다.하지만 내 말 이해하지, 그치?나는 Warrior를 Magage로 대체하여 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행 위에 '메이지'를 썼다면, 그 결과로 나온 행은 '메이지오르'가 될 것입니다.

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

개인의 "작업"이 텍스트에서 일정한 길이인 경우 원하는 개인의 "작업"에 해당하는 텍스트 부분만 변경할 수 있습니다. 이는 senderle의 것과 동일한 아이디어입니다.

하지만 제 말에 따르면, 개인의 특성을 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))

이름이 붙은 파일이 있다고 가정합니다.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

초기 데이터 쓰기, 빈 데이터 인쇄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)

예전에도 같은 요청이 있었는데 결국 진자 템플릿을 하게 되었습니다.로 변경하고 수 .lastname='Meg'그게 제가 생각할 수 있는 가장 효율적이고 빠른 방법입니다.

Dan 
{{ lastname }} 
Warrior 
500 
1 
0
#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()

그것이 당신에게 효과가 있기를 바랍니다.

언급URL : https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python

반응형