从main运行时,函数不运行或返回

2024-04-25 18:20:18 发布

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

我目前正在尝试使用一个.csv文件,该文件大约有70k行和19列。我的代码当前如下所示:

def read_data(filename):
    f = open(filename, "r")
    headers = f.readline().strip().split(",")
    NiceRow = []

    x = 0
    line = f.readline()
    while line:
        NiceRow.append(line.strip().split(","))
        line = f.readline()

        x += 1
    f.close()

    return headers, NiceRow

当我在main下运行此代码时,它不会抛出错误,但不会生成任何可见的数据或返回,因为我尝试在main中该函数之后运行的另一个函数中使用“NiceRow”返回,这会导致错误,因为没有定义“NiceRow”。当我在主函数之外运行此代码时,它可以工作,但只处理少量数据。如果任何人有任何提示或知道为什么它不能在main下生成数据或运行整个文件,将非常感谢您的帮助


Tags: 文件csv数据函数代码readlinemaindef
1条回答
网友
1楼 · 发布于 2024-04-25 18:20:18

正如khelwood提到的,使用csv模块:

import csv

def read_data(filename):
    with open(filename, "r") as f:             # Open file
        reader = csv.reader(f, delimiter=',')  # Use csv module
        lines = list(map(tuple, reader))       # Map csv data to a list of lines
        headers = lines[0]                     # Store headers
        NiceRow = lines[1:]                    # Store rest of lines in NiceRow
    return headers, NiceRow                    # Return headers and NiceRow

相关问题 更多 >