【发布时间】:2018-03-22 04:20:19
【问题描述】:
所以我试图遍历一个 .csv 文件并根据它进行一些计算,我的问题是该文件有 10001 行长,而当我的程序执行时,它似乎只读取了其中的 5001 行。读取数据时我做错了什么,或者我遇到了内存限制或其他某种限制?计算结果很好,但在某些情况下与预期结果有偏差,因此我相信丢失的一半数据可以解决这个问题。
fileName = 'normal.csv' #input("Enter a file name: ").strip()
file = open(fileName, 'r') #open the file for reading
header = file.readline().strip().split(',') #Get the header line
data = [] #Initialise the dataset
for index in range(len(header)):
data.append([])
for yy in file:
ln = file.readline().strip().split(',') #Store the line
for xx in range(len(data)):
data[xx].append(float(ln[xx]))
这是一些示例输出,尚未完全格式化,但最终会:
"""The file normal.csv contains 3 columns and 5000 records.
Column Heading | Mean | Std. Dev.
--------------------+--------------------+--------------------
Width [mm]|999.9797|2.5273
Height [mm]|499.9662|1.6889
Thickness [mm]|12.0000|0.1869"""
由于这是家庭作业,我希望您尝试保持回复有帮助,但不要直接解决问题,谢谢。
【问题讨论】:
-
AFAICT,您在一次迭代中读取 2 行。 “yy”已经包含了一行,调用“file.readline”会将你移到下一行。你应该直接处理“yy”的内容而不调用readline。
标签: python-3.x file csv