Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Formatting a merged txt file

Tags:

python

I want to merge two text files: names.txt and studentid.txt

the name txt contains:

Timmy Wong, Johnny Willis, Jason Prince

the studentid.txt contains:

B5216, B5217, B5218

I want to combine them into a new text file called studentlist.txt with the format I simply want all the commas to become vertical bars

Student_Name             Student_ID
Timmy Wong              | B5216
Johnny Willis           | B5217
Jason Prince            | B5218

So far I don't really know how to format this been reading up some guides and my book but it really isn't helping much.

This is what I done so far

def main():
    one = open( "names.txt", 'r' )
    lines = one.readlines()

    two = open( "studentid.txt", 'r' )
    lines2 = two.readlines()

    outfile = open( "studentlist.txt", 'w' )
    outfile.write( "Student_Name StudentID")
    outfile.writelines( lines + lines2 )

main()

and the output becomes

Student_Name StudentIDTimmy Wong, Johnny Willis, Jason Prince
B5216, B5217, B218

I'm a beginner so go easy on me ><"

like image 270
Jimmy Ly Avatar asked Dec 07 '25 01:12

Jimmy Ly


1 Answers

names = [n.strip() for n in open("names.txt").read().split(",")]
ids = [i.strip() for i in open("studentid.txt").read().split(",")]

print "Student_Name\t| Student_ID"
for n, i in zip(names, ids):
    print "{}\t| {}".format(n, i)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!