[python] 파일에서 텍스트를 검색하고 바꾸는 방법?

Python 3을 사용하여 파일에서 텍스트를 검색하고 바꾸려면 어떻게합니까?

내 코드는 다음과 같습니다.

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

입력 파일:

hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd

위의 입력 파일에서 ‘ram’을 ‘abcd’로 검색하고 바꾸면 매력으로 작동합니다. 그러나 그 반대로 할 때, 즉 ‘abcd’를 ‘ram’으로 바꾸면 일부 정크 문자가 끝납니다.

‘ram’로 ‘abcd’교체

hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd



답변

fileinput내부 편집을 이미 지원합니다. stdout이 경우 파일로 리디렉션 됩니다.

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')


답변

michaelb958에서 지적했듯이 다른 길이의 데이터로 대체 할 수 없으므로 나머지 섹션은 제자리에 배치되지 않습니다. 한 파일에서 읽고 다른 파일에 쓰라고 제안하는 다른 포스터에 동의하지 않습니다. 대신 파일을 메모리로 읽고 데이터를 수정 한 다음 별도의 단계에서 동일한 파일에 씁니다.

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

한 번에 메모리에로드하기에는 너무 큰 작업 할 대용량 파일이 없거나 파일에 데이터를 쓰는 두 번째 단계에서 프로세스가 중단 될 경우 잠재적 인 데이터 손실이 걱정되지 않는 한.


답변

Jack Aidley가 게시하고 JF Sebastian이 지적 했듯이이 코드는 작동하지 않습니다.

 # Read in the file
filedata = None
with file = open('file.txt', 'r') :
  filedata = file.read()

# Replace the target string
filedata.replace('ram', 'abcd')

# Write the file out again
with file = open('file.txt', 'w') :
  file.write(filedata)`

그러나이 코드는 작동합니다 (테스트했습니다).

f = open(filein,'r')
filedata = f.read()
f.close()

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')
f.write(newdata)
f.close()

이 방법을 사용하면 filein과 fileout은 같은 파일 일 수 있습니다. Python 3.3은 파일을 열 때 파일을 덮어 쓰기 때문입니다.


답변

이런 식으로 교체를 할 수 있습니다

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()


답변

을 사용할 수도 있습니다 pathlib.

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)


답변

블록이있는 싱글을 사용하면 텍스트를 검색하고 바꿀 수 있습니다.

with open('file.txt','r+') as f:
    filedata = f.read()
    filedata = filedata.replace('abc','xyz')
    f.truncate(0)
    f.write(filedata)


답변

문제는 동일한 파일을 읽고 쓰는 것에서 비롯됩니다. 오히려 개방보다 fileToSearch쓰기, 실제 임시 파일을 열고 작업을 완료하고 닫은 후 다음 tempFile, 사용 os.rename을 통해 새 파일을 이동합니다 fileToSearch.