source

파일에서 텍스트를 검색하고 바꾸려면 어떻게 해야 합니까?

goodcode 2022. 9. 18. 21:34
반응형

파일에서 텍스트를 검색하고 바꾸려면 어떻게 해야 합니까?

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'으로 대체하면 마지막에 정크 캐릭터가 남습니다.

'abcd'를 'ram'으로 대체

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

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)

한번에 메모리에 로드하기에는 너무 큰 대용량 파일이 있거나 파일에 데이터를 쓰는 두 번째 단계에서 프로세스가 중단될 경우 데이터 손실이 우려되는 경우가 아니라면 말입니다.

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

잭 에이들리와 J.F.가 게시한 것처럼.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()

이 방법을 사용하면 파일 입력과 파일 아웃이 동일한 파일이 될 수 있습니다. 왜냐하면 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)

(install python-param)

from pyutil import filereplace

filereplace("somefile.txt","abcd","ram")

의 모든 을 "으로. "abcd"는 "ram"으로 바꿉니다.
는 또한 "regex"를 를 지원합니다.regex=True

from pyutil import filereplace

filereplace("somefile.txt","\\w+","ram",regex=True)

면책사항:작성자입니다(https://github.com/MisterL2/python-util)

이 답변은 저에게 효과가 있습니다.파일을 읽기 모드로 엽니다.파일을 문자열 형식으로 읽습니다.원하는 대로 텍스트를 바꿉니다.파일을 닫습니다.파일을 다시 쓰기 모드로 엽니다.마지막으로 대체된 텍스트를 동일한 파일에 씁니다.

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

답변이 늦었지만 텍스트파일 내에서 검색 및 치환에 사용하는 것은 다음과 같습니다.

with open("test.txt") as r:
  text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
  w.write(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.

한번에 전체 파일에 대한 나의 변형인 한마디.

나는 기억을 읽었다.

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)

나는 readlines 대신 읽기 쓰려고 했다.

with open('dummy.txt','r') as file:
    list = file.readlines()
print(f'before removal {list}')
for i in list[:]:
        list.remove(i)

print(f'After removal {list}')
with open('dummy.txt','w+') as f:
    for i in list:
        f.write(i)

나는 이 금액을 받았다.

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")
os.chdir(Dir)

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()
def word_replace(filename,old,new):
    c=0
    with open(filename,'r+',encoding ='utf-8') as f:
        a=f.read()
        b=a.split()
        for i in range(0,len(b)):
            if b[i]==old:
                c=c+1
        old=old.center(len(old)+2)
        new=new.center(len(new)+2)
        d=a.replace(old,new,c)
        f.truncate(0)
        f.seek(0)
        f.write(d)
    print('All words have been replaced!!!')

답을 이미 언급한 게다가, 여기 왜 너는 끝에 몇몇 임의의 글자들 가지고 있는 설명: 있다.
.r+ 「」가 아닙니다.w은 ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ 중요한 차이점입니다.w 지우는 , 파일 을 지웁니다.r+그렇지 않다.
이것은 만약 당신의 파일 콘텐츠고 여기에"www"를 쓰"123456789"한"www456789"시작한다는 뜻이죠.그것은 새로운 입력으로,지만 남아 있는 입력하지 않는 잎들은 캐릭터들을 덮어씁니다.
, 파일 내용을 클리어 하려면 , 「 내용을 하려면 , 「파일 내용」truncate(<startPosition>)을 먼저 후, 을 실행하는 truncate(0)그리고 그것을 한번에 모두 쓰는 것입니다
아니면:내 도서관을 이용할 수 있다.d

저도 같은 문제가 생겼어요.문제는 변수에 .txt를 로드할 때 문자열 배열처럼 사용하는 반면 문자열 배열로 사용한다는 것입니다.

swapString = []
with open(filepath) as f: 
    s = f.read()
for each in s:
    swapString.append(str(each).replace('this','that'))
s = swapString
print(s)

python에서는 sed, awk 또는 grep를 사용할 수 있습니다(몇 가지 제한이 있습니다).여기 아주 간단한 예가 있습니다.그것은 파일에서 바나나를 바나나투스 페이스트로 바꿉니다.편집해서 사용할 수 있습니다.(테스트를 해봤는데...주의: 윈도에서 테스트하는 경우 "sed" 명령어를 설치하고 경로를 먼저 설정해야 합니다.)

import os 
file="a.txt"
oldtext="Banana"
newtext=" BananaToothpaste"
os.system('sed -i "s/{}/{}/g" {}'.format(oldtext,newtext,file))
#print(f'sed -i "s/{oldtext}/{newtext}/g" {file}')
print('This command was applied:  sed -i "s/{}/{}/g" {}'.format(oldtext,newtext,file))

파일의 결과를 직접 적용하려면 , Windows 의 경우는 「type」, Linux 의 경우는 「cat」를 참조해 주세요.

####FOR WINDOWS:
os.popen("type " + file).read()
####FOR LINUX:
os.popen("cat " + file).read()

저는 Jayram Singh의 투고를 약간 수정하여 '!'라는 글의 모든 인스턴스를 제가 원하는 숫자로 바꾸었습니다.한 줄에 두 번 이상 발생하고 반복하고 싶은 캐릭터를 수정하고 싶은 사람에게 도움이 될 수 있다고 생각했습니다.그게 도움이 됐으면 좋겠어요.추신- 저는 코딩에 익숙하지 않기 때문에, 제 투고가 조금이라도 부적절했다면 사과드립니다만, 이것은 저에게 효과가 있었습니다.

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1
        else:
            f2.write(word)
f1.close()
f2.close()

저는 이 문제를 코스의 연습으로 풀었습니다.파일 열기, 문자열 찾기 및 바꾸기, 새 파일에 쓰기입니다.

class Letter:

    def __init__(self):

        with open("./Input/Names/invited_names.txt", "r") as file:
            # read the list of names
            list_names = [line.rstrip() for line in file]
            with open("./Input/Letters/starting_letter.docx", "r") as f:
                # read letter
                file_source = f.read()
            for name in list_names:
                with open(f"./Output/ReadyToSend/LetterTo{name}.docx", "w") as f:
                    # replace [name] with name of the list in the file
                    replace_string = file_source.replace('[name]', name)
                    # write to a new file
                    f.write(replace_string)


brief = Letter()

이를 사용하면 대소문자를 구분하는 두 줄에 걸쳐 단어를 분할하는 등 대체 프로세스를 보다 효과적으로 제어할 수 있습니다.또한 문자열을 찾을 수 없는 경우 리소스 낭비를 방지하기 위해 사용할 수 있는 일치 수를 반환합니다.

import re

file = # path to file

# they can be also raw string and regex
textToSearch = r'Ha.*O' # here an example with a regex
textToReplace = 'hallo'

# read and replace
with open(file, 'r') as fd:
    # sample case-insensitive find-and-replace
    text, counter = re.subn(textToSearch, textToReplace, fd.read(), re.I)

# check if there is at least a  match
if counter > 0:
    # edit the file
    with open(file, 'w') as fd:
        fd.write(text)

# summary result
print(f'{counter} occurence of "{textToSearch}" were replaced with "{textToReplace}".')

일부 정규식:

  • 의 짧은 형식의 플래그를 추가합니다.re.IGNORECASE, 대소문자를 구분하지 않는 경우
  • 멀티라인 치환용re.subn(r'\n*'.join(textToSearch), textToReplace, fd.read())(데이터에 따라서도)'\n{,1}'이 경우 주의해 주십시오.textToSearch정규식이 아닌 순수 문자열이어야 합니다!
def findReplace(find, replace):

    import os 

    src = os.path.join(os.getcwd(), os.pardir) 

    for path, dirs, files in os.walk(os.path.abspath(src)):

        for name in files: 

            if name.endswith('.py'): 

                filepath = os.path.join(path, name)

                with open(filepath) as f: 

                    s = f.read()

                s = s.replace(find, replace) 

                with open(filepath, "w") as f:

                    f.write(s) 

다음과 같은 경우:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text = f.read()
    f.write(text.replace(word, replacement))

언급URL : https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file

반응형