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

Question:

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

Asked By: poLi

||

Answers:

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)
Answered By: Thickycat

something you could do is the following

import re


# This opens the file in read mode
with open('Original.txt', 'r') as file:
    # Read the contents of the file
    contents = file.read()

# Seems that your original file has line breaks to each domain so
# you could replace it with the word "OR" using a regular expression
contents = re.sub(r'n+', ' OR ', contents)

# Then you should open the file in write mode
with open('Original.txt', 'w') as file:
    # and finally write the modified contents to the file
    file.write(contents)

a suggestion is, maybe you want to try first writing in a different file to see if you are happy with the results (or do a copy of Original.txt just in case)


with open('AnotherOriginal.txt', 'w') as file:
    file.write(contents)
Answered By: Darkaico
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.