Reputation: 93
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 ><"
Upvotes: 3
Views: 168
Reputation: 251186
with open('data.txt') as f1,open('data1.txt') as f2,open('sudentlist.txt') as f3:
line=f1.readline().strip() #read the first line of names file
names=map(str.strip,line.split(',')) #split the line by "," and then apply strip()
line=f2.readline().strip() #read the first line of ID file
ids=map(str.strip,line.split(',')) #split the line by "," and then apply strip()
f3.write("{0:25}{1}\m".format("Student_Name","Student_Id"))
for name,i in zip(names,ids): #use zip() to fetch data from both lists
f3.write("{0:25}|{1}\n".format(name,i)) #use write() instead of print to write it to a file
output:
Student_Name Student_Id
Timmy Wong |B5216
Johnny Willis |B5217
Jason Prince |B5218
Upvotes: 0
Reputation: 2234
names = [n.strip() for n in open("names.txt").read().split(",")]
student_ids = [i.strip() for i in open("studentid.txt").read().split(",")]
outfile = open("studentlist.txt", 'w')
outfile.write("Student_Name\tStudent_ID\n")
for current_name, current_id in zip(names, student_ids):
outfile.write(current_name + "\t|" + current_id + "\n")
outfile.close()
Upvotes: 0
Reputation: 142256
Untested, but you want something similar to:
import csv
with open('names.txt') as nf, open('studentid.txt') as sf, open('output.txt','wb') as pf:
csvnf = csv.reader(nf)
csvsf = csv.reader(sf)
csvpf = csv.writer(pf, delimiter='|')
for name_student in zip(csvnf, csvsf):
pf.writerow( name_student )
Upvotes: 0
Reputation:
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)
Upvotes: 4