从主程序运行时,函数不运行或不提供回报

问题描述 投票:-1回答:1

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

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'return ,这会导致错误,因为未定义'NiceRow'。当我在主要功能之外运行此代码时,它可以工作,但仅处理少量数据。如果任何人有任何提示或知道为什么它不能在main下生成数据或运行整个文件,将不胜感激。

python python-3.x csv return
1个回答
0
投票

正如凯尔伍德所说,使用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
© www.soinside.com 2019 - 2024. All rights reserved.