3

我想合并两个文本文件: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

我是初学者所以放轻松><"

4

4 回答 4

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)
于 2012-09-05T12:35:28.373 回答
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
于 2012-09-05T12:37:01.407 回答
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 )
于 2012-09-05T12:37:57.937 回答
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()
于 2012-09-05T12:40:07.447 回答