我目前正在尝试使用约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下生成数据或运行整个文件,将不胜感激。
正如凯尔伍德所说,使用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