我想合并两个文本文件:names.txt和studentid.txt
名称txt包含:
Timmy Wong, Johnny Willis, Jason Prince
studentid.txt包含:
B5216, B5217, B5218
我想将它们组合成一个名为studentlist.txt的新文本文件,格式我只想让所有逗号成为竖线
Student_Name Student_ID
Timmy Wong | B5216
Johnny Willis | B5217
Jason Prince | B5218
到目前为止,我真的不知道如何格式化,这已经阅读了一些指南和我的书,但它确实没有多大帮助。
这是我到目前为止所做的事情
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()
,输出变为
Student_Name StudentIDTimmy Wong, Johnny Willis, Jason Prince
B5216, B5217, B218
我是初学者,所以对我很轻松><“
答案 0 :(得分:4)
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)
答案 1 :(得分:0)
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
<强>输出:强>
Student_Name Student_Id
Timmy Wong |B5216
Johnny Willis |B5217
Jason Prince |B5218
答案 2 :(得分:0)
未经测试,但您需要类似的内容:
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 )
答案 3 :(得分:0)
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()