The below Python 3 program scans 4 files a.txt
, b.txt
, c.txt
, d.txt
and then outputs the read data into a file output.txt
in a formatted way. The first line of each file is guaranteed to have a header and the second line of each file will be blank. I'm required to scan those four files.
Program:
def main():
with open('a.txt', 'r') as file_a, open('b.txt', 'r') as file_b, open('c.txt', 'r') as file_c, open('d.txt', 'r') as file_d:
lines1, lines2, lines3, lines4 = file_a.readlines(), file_b.readlines(), file_c.readlines(), file_d.readlines()
lines = [lines1, lines2, lines3, lines4]
number_of_spaces = 5
assert len(lines1) == len(lines2) == len(lines3) == len(lines4), "Error. Different number of lines found in the files"
row, column = 0, 1
with open('output.txt', 'w') as output:
while row < len(lines):
output.write(lines[row][0].strip() + ' ' * number_of_spaces)
row += 1
output.write('\n')
row = 0
while column < len(lines1):
while row < len(lines):
output.write(lines[row][column].strip() + ' ' * (number_of_spaces + len(lines[row][0].strip()) - len(lines[row][column].strip())))
row += 1
output.write('\n')
column += 1
row = 0
if __name__ == "__main__":
main()
When executed gives output.txt
:
Sl.No Elements Abbreviation Mass
1 Hydrogen H 1
2 Helium He 4
3 Lithium Li 7
4 Beryllium Be 9
...
98 Californium Cf 251
99 Einsteinium Es 252
100 Fermium Fm 257
Is there any room for improvement?
Additional information (if necessary):
Note that ...
in the files mean that there are a lot of similar data and not that the file contains those dots.
a.txt
:
Sl.No
1
2
3
...
99
100
b.txt
:
Elements
Hydrogen
Helium
Lithium
Beryllium
...
Californium
Einsteinium
Fermium
c.txt
:
Abbreviation
H
He
Li
Be
...
Cf
Es
Fm
d.txt
:
Mass
1
4
7
9
...
251
252
257