티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to search and replace text in a file?
파일의 텍스트를 검색하고 바꾸는 방법은 무엇입니까?
문제 내용
How do I search and replace text in a file using Python 3?
파이썬 3을 사용하여 파일의 텍스트를 검색하고 바꾸려면 어떻게 해야 합니까?
Here is my code:
제 코드는 다음과 같습니다.
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...' )
Input file:
입력 파일:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
When I search and replace 'ram' by 'abcd' in above input file, it works as a charm. But when I do it vice-versa i.e. replacing 'abcd' by 'ram', some junk characters are left at the end.
위의 입력 파일에서 'ram'을 'abcd'로 검색하여 대체하면 매력적으로 작동합니다. 하지만 내가 그것을 반대로 할 때, 즉 'abcd'를 'ram'으로 대체할 때, 일부 정크 캐릭터들은 마지막에 남습니다.
Replacing 'abcd' by 'ram'
'abcd'를 'ram'으로 대체
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
높은 점수를 받은 Solution
As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.
michael b958에서 지적한 바와 같이, 다른 길이의 데이터로 대체할 수 없습니다. 나머지 섹션은 제자리에 배치되지 않기 때문입니다. 저는 당신이 한 파일을 읽고 다른 파일에 글을 쓰라고 제안하는 다른 포스터들에 동의하지 않습니다. 대신, 파일을 메모리로 읽고, 데이터를 수정한 다음, 별도의 단계로 동일한 파일에 기록할 것입니다.
# 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)
Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.
너무 커서 메모리에 한 번에 로드할 수 없는 대용량 파일이 있거나 파일에 데이터를 쓰는 두 번째 단계에서 프로세스가 중단될 경우 데이터 손실이 우려되는 경우가 아니라면 말입니다.
가장 최근 달린 Solution
This answer works for me. Open the file in read mode. Read the file in string format. Replace the text as intended. Close the file. Again open the file in write mode. Finally, write the replaced text to the same file.
이 답은 제게 효과가 있습니다. 파일을 읽기 모드로 엽니다. 파일을 문자열 형식으로 읽습니다. 텍스트를 원래대로 바꿉니다. 파일을 닫습니다. 파일을 다시 쓰기 모드로 엽니다. 마지막으로, 대체된 텍스트를 동일한 파일에 작성합니다.
with open("file_name", "r+") as text_file:
texts = text_file.read()
texts = texts.replace("to_replace", "replace_string")
with open(file_name, "w") as text_file:
text_file.write(texts)
except FileNotFoundError as f:
print("Could not find the file you are trying to read.")
출처 : https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file
'개발 > 파이썬' 카테고리의 다른 글
데이터프레임에서 두 개의 열 하나로 합치기 (0) | 2022.12.16 |
---|---|
파일에서 특정 줄(줄 번호로) 읽기 (0) | 2022.12.16 |
읽기와 쓰기 모두를 위해 파일을 여는 방법은 무엇입니까? (0) | 2022.12.14 |
값에 따라 리스트 아이템을 삭제하는 쉬운 방법 (0) | 2022.12.14 |
'ValueError: numpy.ndarray size changed, may indicate binary incompatibility' 에러 수정하기 (0) | 2022.12.14 |