How to search and replace text in a file?

前端 未结 15 2197
傲寒
傲寒 2020-11-21 20:29

How do I search and replace text in a file using Python 3?

Here is my code:

import os
import sys
import fileinput

print (\"Text to search for:\")
te         


        
相关标签:
15条回答
  • 2020-11-21 21:10

    Like so:

    def find_and_replace(file, word, replacement):
      with open(file, 'r+') as f:
        text = f.read()
        f.write(text.replace(word, replacement))
    
    0 讨论(0)
  • 2020-11-21 21:19

    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()
    
    0 讨论(0)
  • 2020-11-21 21:21

    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.

    0 讨论(0)
  • 2020-11-21 21:22

    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)
    
    0 讨论(0)
  • 2020-11-21 21:22
    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) 
    
    0 讨论(0)
  • 2020-11-21 21:25

    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.

    # 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.

    0 讨论(0)
提交回复
热议问题