微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

所以在我的python代码运行后,我输入了输入,程序就停止了不知道逻辑错误是什么

如何解决所以在我的python代码运行后,我输入了输入,程序就停止了不知道逻辑错误是什么

我正在尝试为 CSV 文件创建一个简单的解析器。我正在尝试使用最简单的方法来查看解析器以查找值(行)。

import csv
"""
with open('C:/MAIL07072021180029.csv','r') as file:
     proxy = csv.reader(file)
     for row in proxy:
         print(row[0])

"""

identifyingnumber = input("What is the number? ")

with open('C:/MAIL07072021180029.csv','r') as file:
    data = csv.reader(file)
    for row in data:
        if row[1] == (identifyingnumber):
            print(row)

在我运行代码并输入代理号码后(识别号码,我的excel中的数据)。程序就停了?它没有打印行。

这是我的 csv 文件中的示例数据:

Card Identifying Sequence
1873356

我通过取出如果,该行打印成功,识别号来打印第 0 行。

这是某种逻辑错误吗?我想不通。

解决方法

您的 csv 文件中可能没有识别号,在这种情况下,由于您的“if”语句,不会打印任何内容。你可以检查你是否找到了这个数字,如果找到了,中断(如果你不想检查其他行的另一个数字实例),如果没有,打印你从未找到这个数字。>

with open('C:/MAIL07072021180029.csv','r') as file:
    data = csv.reader(file)
    found = False
    for row in data:
        if row[1] == (identifyingnumber):
            print(row)
            found = True
            break    # if you don't want to look for more instances of identifyingnumber
    if not found:   # aka found == False
        print('I did not find any row[1] equal to',identifyingnumber)    

我强烈推荐 Pandas 来帮助您完成任务。在 Pandas 中打开 csv,然后一次检查所有行的值,而不是遍历行。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

import pandas as pd
df = pd.read_csv('C:/MAIL07072021180029.csv')
col1 = df.columns[1]
dfi = df[df[col1] == identifyingnumber]
dfi = dfi.reset_index()
print(dfi['index'].tolist())        # there could be more than 1 row with the identifier

编辑以将我们讨论中的所有内容放在评论中:

file_list = ['C:/MAIL07072021180029.csv','C:/other_file.csv']
for f in file_list:
    with open(f,'r') as file:
        data = csv.reader(file)
        found = False
        for row in data:
            if found:   # aka found == True - if any column found the value,break to stop iterating
                break
            for col in range(1,len(row)):   # start at 1 to skip col 0
                if row[col] == identifyingnumber:  # (identifyingnumber) is a tuple(),you probably don't want that
                    print(row)
                    found = True
                    break    # if you don't want to look for more instances of identifyingnumber
        if not found:   # aka found == False
            print('I did not find any row[1] equal to',identifyingnumber)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。