3

names.txtとstudentid.txtの2つのテキストファイルをマージしたい

名前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 に答える