Skip to content
Advertisement

Editing a txt file in Python to edit the formatting and then create new txt file

and thank you for taking the time to read this post. This is literally my first time trying to use Python so bare with me.

My Target/Goal: Edit the original text file (Original .txt file) so that for every domain listed an “OR” is added in between them (below target formatting image). Any help is greatly appreciated.

I have been able to google the information to open and read the txt file, however, I am not sure how to do the formatting part.

Script

Original .txt file

Target formatting

Advertisement

Answer

You can achieve this in a couple lines as:

with open(my_file) as fd:
    result = fd.read().replace("n", " OR ")

You could then write this to another file with:

with open(formatted_file, "w") as fd:
     fd.write(result)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement