patternpythonMinor
Program that reads 4 files and outputs contents of it into another file after formatting it
Viewed 0 times
afterformattingfileintoprogramcontentsreadsfilesthatoutputs
Problem
The below Python 3 program scans 4 files
Program:
When executed gives
Is there any room for improvement?
Additional information (if necessary):
Note that
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 257Is there any room for improvement?
Additional information (if necessary):
Note that
... in the files meSolution
I think that
The above is just a basic example, you will want to:
zip can save you some work: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:
for content in zip(file_a.readlines(), file_b.readlines(),
file_c.readlines(), file_d.readlines()):
print(content)The above is just a basic example, you will want to:
- Add error checking (
asserting for example)
- Add an output file
- Add necessary spaces
Code Snippets
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:
for content in zip(file_a.readlines(), file_b.readlines(),
file_c.readlines(), file_d.readlines()):
print(content)Context
StackExchange Code Review Q#94648, answer score: 2
Revisions (0)
No revisions yet.