读取2.txt文件,访问其中的数据,然后打印

2024-09-29 23:20:25 发布

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

我不太确定这个问题是否已经得到了回答,我也不确定如何查找它,所以我在这里试试运气

我对Python相当陌生,需要解决这个参数:使用从2.txt文件中提取的数据创建一个新文件

我有以下.txt文件:

# empList
# format: Employee number, First name, Last name, Department, Rate
201701013,Simona,Morasca,Finance,450;
201011003,Mitsue,Tollner,Marketing,750;
201409015,Leota,Dilliard,Finance,365;
199512017,Sage,Wieser,MIS,750;
199708003,Kris,Marrier,Admin,750;
# empMR
# format: Employee number, month, days worked
201612010,4,18;
201710017,4,12;
201701013,4,20;
201011003,4,24;
201409015,4,26;
199512017,4,28;
199708003,4,21;

我努力实现的目标是:

  1. 我应该能够访问这两个文件中的数据
  2. 获取数据后创建一个新文件

我有这个代码,我正在试验,但唉,我仍然无法解决这个问题

while True:
    with open("empList.txt", "r") as f1, open("empMR.txt", "r") as f2:
        data1 = f1.read()
        data2 = f2.read()
    x1 = data1.strip().split(';')
    x2 = data2.strip().split(',')
    for (line1, line2) in (x1, x2):
        line1 = line1.strip().split(',')
        print(line2)

与此同时,我正在尝试先打印所有内容,以便查看代码是否正常工作,因为编写一个文件需要花费大量时间,打印时也一样

现在是所需的输出:

我应该从empList获得:员工编号、员工姓名、部门和费率;然后从empMR开始,我应该得到这个月,而且这些天都在工作。把它打印出来(或者用这些数据创建一个新文件),这样我就可以继续工作了

我不知道我说的是否有道理,但如果你需要澄清,请告诉我。谢谢


Tags: 文件数据代码nametxtformatnumberemployee
2条回答

您可以这样做:

with open('empList.txt', 'r') as w1, open("empMR.txt", "r") as w2:
    list1 = [each.rstrip(';').split(',') for each in w1.read().splitlines()]
    list2 = [each.rstrip(';').split(',') for each in w2.read().splitlines()]

new_data = [(e1+e2[1:]) for e1 in list1 for e2 in list2 if e1[0] == e2[0]]
for each in new_data:
    print(each)

输出将是一个列表。但您可以轻松地修改此选项:

['201701013', 'Simona', 'Morasca', 'Finance', '450', '4', '20']
['201011003', 'Mitsue', 'Tollner', 'Marketing', '750', '4', '24']
['201409015', 'Leota', 'Dilliard', 'Finance', '365', '4', '26']
['199512017', 'Sage', 'Wieser', 'MIS', '750', '4', '28']
['199708003', 'Kris', 'Marrier', 'Admin', '750', '4', '21']

以下是您可以做的:

with open('empList.txt','r') as f1, open('empMR.txt','r') as f2:
    l1, l2 = f1.readlines(), f2.readlines()

for s1 in l1:
    a1 = s1.split(',')
    for s2 in l2:
        a2 = s2.split(',')
        if a1[0] == a2[0]: # If the employee numbers match
            num = a1[0]
            fna = a1[1]
            lna = a1[2]
            dpt = a1[3]
            rte = a1[4][:-2]
            mth = a2[1]
            wrk = a2[2][:-2]
            print(num,fna,lna,dpt,rte,mth,wrk)

输出:

201701013 Simona Morasca Finance 450 4 20
201011003 Mitsue Tollner Marketing 750 4 24
201409015 Leota Dilliard Finance 365 4 26
199512017 Sage Wieser MIS 750 4 28
199708003 Kris Marrier Admin 75 4 2

相关问题 更多 >

    热门问题