繁体   English   中英

Function 从 main 运行时不运行或返回

[英]Function doesn't run or give returns when run from main

我目前正在尝试使用大约 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 之后运行的另一个 function 中使用“NiceRow”返回,这导致错误,因为未定义“NiceRow”。 当我在我的主 function 之外运行此代码时,它可以工作,但只处理少量数据。 如果有人有任何提示或知道为什么它不会在 main 下生成数据或运行整个文件,我们将不胜感激。

正如 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM