Home > Net >  Using python to replace strings with new strings in python
Using python to replace strings with new strings in python

Time:11-17

I got this code below to test out but it doesn't work the way it's supposed to.

Note that I'm using MacM1 and use vscode as IDE.

fin = open("file.txt", "rt")

#output file to write the result to
fout = open("out.txt", "wt")

#for each line in the input file
for line in fin:

    #read replace the string and write to output file
    fout.write(line.replace('old', 'new'))

#close input and output files
fin.close()
fout.close()

I've the file.txt ready with strings in it including 'old'. Once I run the program, the new file out.txt was created but it is empty. Vscode doesn't show errors so I don't know where to fix it. Thanks!

CodePudding user response:

  1. You should always use context manager for IO.
  2. open with "t" is not necessary since t stands for text mode, which is default.
# main.py
with open("file.txt", "r") as fin, open("out.txt", "w") as fout:
    for line in fin.readlines(): # using for line in fin also works
        fout.write(line.replace("old", "new"))
❯ python3 main.py
❯ cat file.txt
test old
test                                                                                                                                            
❯ cat out.txt
test new
test    

CodePudding user response:

Unless your input file is massive, then there's no reason to read it line by line. The following will suffice:

with open('file.txt') as fin, open('out.txt', 'w') as fout:
  fout.write(fin.read().replace('old', 'new'))

CodePudding user response:

Actually the problem in your code that you only open the file without reading it:

fin = open("file.txt", "rt")
data = fin.read(4)    # read the first 4 characters
data = fin.read()     # read till end of file
data = fin.readline() # read one line of the file at current cursor
data = fin.readlines() # read till end of file line by line and return it in list

It's recommended to put opening, reading, writing file operations between try catch block if any exception during reading file and writing to it happened, you can either reading the file line by line using for loop with open() method or using read(), readline() methods:

try:
   fin = open("file.txt", "r")
   #output file to write the result to
   fout = open("out.txt", "w")
   for line in fin:
   #read replace the string and write to output file
   fout.write(line.replace('old', 'new'))
except Exception as e:
   print("Error", e, "occurred.")
finally:
   fin.close()
   fout.close()
   

For more info about I/O file operations check reference.

  • Related