gpt4 book ai didi

Python:格式化合并的 txt 文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:50 25 4
gpt4 key购买 nike

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

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

最佳答案

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)

关于Python:格式化合并的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12281477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com