Programing

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

crosscheck 2020. 5. 28. 07:58
반응형

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


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)

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.


As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:

 # 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)`

But this code WILL work (I've tested it):

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

Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.


You can do the replacement like this

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

Your problem stems from reading from and writing to the same file. Rather than opening fileToSearch for writing, open an actual temporary file and then after you're done and have closed tempFile, use os.rename to move the new file over fileToSearch.


You can also use 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)

My variant, one word at a time on the entire file.

I read it into memory.

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)

I have done this:

#!/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!!!')

(pip install python-util)

from pyutil import filereplace

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

The second parameter (the thing to be replaced, e.g. "abcd" can also be a regex)
Will replace all occurences


I recommend its worth checking it out this small program. Regular expressions are the way to go.

https://github.com/khranjan/pythonprogramming/tree/master/findandreplace


I modified Jayram Singh's post slightly in order to replace every instance of a '!' character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I'm very new at coding so apologies if my post is inappropriate in any way, but this worked for me.

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

With a single with block, you can search and replace your text:

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

def findReplace(find, replace):

import os 

src = os.path.join(os.getcwd(), os.pardir) **`//To get the folder in which files are present`** 

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) 

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

반응형