【问题标题】:python nested loop using files and if condition not workingpython嵌套循环使用文件和if条件不起作用
【发布时间】:2014-07-05 20:41:23
【问题描述】:

我有:

master = open('master.txt', 'r')
transaction = open('transaction.txt', 'r')

master_list = []
employee_list = []


    for line in master:
        # split the line
        record = line.split(',')
        # extract id from record
        emp_id = record[0]
        # add id to list
        employee_list.append(emp_id)

        for li in transaction:
            # split the line
            rec = li.split(',')
            i_d = rec[3]
            print(i_d)

这按预期工作并输出

001
001
001
001
001
002
002
002
002
002
003
003
003
003
003
004
004
004
004
004
005
005
005
005
005

但是如果我在这样的嵌套循环中使用 if 语句:

for li in transaction_file:
            # split the line
            rec = li.split(',')
            i_d = rec[3]
            if i_d == emp_id:
                print(emp_id)

我只得到 001 001 001 001 001

这是为什么?

【问题讨论】:

  • @akonsu 你在拖钓吗,兄弟?

标签: python file for-loop


【解决方案1】:

您永远不会回滚您的交易文件;您在主循环的第一个循环中通过它一次。

您的结构可能不是最好的,但是:

for line in master:
    # split the line
    record = line.split(',')
    # extract id from record
    emp_id = record[0]
    # add id to list
    employee_list.append(emp_id)

    transaction.seek(0)
    for li in transaction:
        # split the line
        rec = li.split(',')
        i_d = rec[3]
        print(i_d)

每次迭代之前,transaction.seek(0) 都会将您倒回到文件的开头(将阅读位置移动到文件的开头)。

【讨论】:

  • 天啊,你是神!谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-08-26
  • 2015-05-22
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 2019-10-01
  • 2020-03-18
  • 2013-12-04
相关资源
最近更新 更多