【问题标题】:Function doesn't run or give returns when run from main从 main 运行时函数不运行或返回
【发布时间】:2020-03-12 17:33:46
【问题描述】:

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

【问题讨论】:

  • 为什么不使用csv 模块? docs.python.org/3.7/library/csv.html
  • 您显示的代码没有明显问题。如果调用此代码没有达到您的预期,您可能应该显示调用代码,因为它可能没有按照您的意图执行,即使此代码没问题。

标签: python python-3.x csv return


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 2014-01-09
    • 2019-09-06
    • 2014-12-18
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多