Python:格式化合并的txt文件

2024-10-02 06:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我要合并两个文本文件:名称.txt以及studentid.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

我是个初学者,所以请对我宽容一点>;<


Tags: 文件nametxtopenstudentoutfile文本文件jason
3条回答
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

未经测试,但您希望类似于:

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 )
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)

相关问题 更多 >

    热门问题