Python Split Lines and write it in file

Viewed 356

I was trying to code a python program so that I can read a txt file that has jumbled up things like date, time, name and status in each line and I want to split all file's line and do something like shown below. I have also searched in Internet and I did not find it.

My txt file is:

12/30/20
4:48 PM
PY New
Refund
12/30/20
4:24 PM
Not Refund
Done



And I want that program to write something like this:

  Date           Time           Name         Status
12/30/20        4:48 PM        PY New        Refund
12/30/20        4:24 PM        Not Refund    Done



Here is my python code:
filename = "RawData.txt"
with open(filename, "r") as fin:
    for line in fin:
        while 3 > 0:
            print(line.strip(""))
            break

with open("ProcessedData.txt", "w") as fin:
    #"newdata" is the variable that will store the data after splitting in 3 lines.
    fin.write(newdata)
1 Answers

Here is how you can use the third parameter of the range() method, the step:

filename = "RawData.txt"
with open(filename, "r") as fin, open("ProcessedData.txt", "w") as fin2:
    fin2.write("  Date           Time           Name         Status" + "\n")
    lines = fin.read().splitlines()
    for i in range(0, len(lines), 4):
        fin2.write(''.join(line.ljust(15) for line in lines[i:i+4]) + "\n")

ProcessedData.txt result:

  Date           Time           Name         Status
12/30/20       4:48 PM        PY New         Refund         
12/30/20       4:24 PM        Not Refund     Done           

Now, if you look at the resulting data inside ProcessedData.txt as a txt file, it might not look so neat. The reason would be because of the font.

Related