使用Python查询多个文本文件以合并列并显示输出

2024-09-26 17:53:47 发布

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

我有两个文本文件,其中包含如下所示的数据,我想以Python中描述的格式显示输出。我将PyCharm IDE与python3.0结合使用。我还尝试在Python中使用dictionary和list,但未能正确获得它。你知道吗

[文件1.txt]

2|Stacey|Tucker
4|Simi|Mirza
9|Naved|Singh
6|Ram|Patel
7|Joe|Pruth

[文件2.txt]

2|26
6|17
9|30
4|31
7|35

所需打印输出:

2  Tucker,Stacey   26
4   Mirza,Simi      31
9   Singh,Naved     30
6   Patel,Ram       17
7   Pruth,Joe       35

谁能给我一个建议吗?你知道吗


Tags: 文件数据txt格式ram文本文件joetucker
1条回答
网友
1楼 · 发布于 2024-09-26 17:53:47

如果文件不是很大,可以读取每个文件,将行附加到一个列表中(每个文件一个)。然后拆分“|”上的行。这将为您提供要匹配的索引[0]。因此,您可以将每个列表的各个部分合并到一个新的列表中进行输出。 新列表中的[0]来自任一列表,[2]来自file1list+“,”+[1]来自filelist1+[1]来自filelist2。你知道吗

#merglist.py

student_id = [] 
grade = []

file1 = open("file1.txt")
file2 = open("file2.txt")

f1 = file1.readlines()
for line in f1:
    student_id.append(line.split('|'))

f2 = file2.readlines()
for line in f2:
    grade.append(line.split('|'))

for g in grade:
    for s in student_id:
        if g[0]==s[0]:
            newline = g[0] + " " + s[2].strip("\n") + ", " + s[1] + " "+ g[1].strip("\n")
            print newline

| => python2 mergelists.py 
2 Tucker, Stacey 26
6 Patel, Ram 17
9 Singh, Naved 30
4 Mirza, Simi 31
7 Pruth, Joe 35

相关问题 更多 >

    热门问题