简体   繁体   English

CSV阅读器无法读取整个文件

[英]CSV reader not reading entire file

I have looked at previous answers to this question, but in each of those scenarios the questioners were asking about something specific they were doing with the file, but the problem occurs for me even when I am not. 我已经看过这个问题的先前答案,但在每个场景中,提问者都在询问他们对文件做了哪些具体的事情,但即使我没有,也会出现问题。

I have a .csv file of 27,204 rows. 我有一个27,204行的.csv文件。 When I open the python interpreter: 当我打开python解释器时:

python
import csv
o = open('btc_usd1hour.csv','r')
p = csv.reader(o)
for row in p:
  print(row)

I then only see roughly the last third of the document displayed to me. 然后我只看到显示给我的文档的最后三分之一。

Try the following code 请尝试以下代码

import csv

fname = 'btc_usd1hour.csv'
with open(fname, newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

It is difficult to tell what is the problem without having the sample. 没有样品很难说出问题是什么。 I guess the problem would be removed if you add that newline='' for opening the file. 我想如果你添加newline=''来打开文件,问题就会被删除。

Use the with construct to close the file automatically. 使用with构造自动关闭文件。 Use the f name for a file object when no further explanation is needed. 如果不需要进一步说明,请使用f名称作为文件对象 Store the file name to fname to make future modifications easier (and also for easy copying the code fragment for your later programs). 将文件名存储到fname以便将来修改更容易(并且还可以轻松复制以后程序的代码片段)。

olisch may be right that the console just scrolled so fast you could not see the result. olisch可能是正确的,控制台只是滚动得如此之快,你无法看到结果。 You can write the result to another text file like this: 您可以将结果写入另一个文本文件,如下所示:

with open(fname, newline='') as fin,\
     open('output.txt', 'w') as fout:
    reader = csv.reader(fin)
    for row in reader:
        fout.write(repr(row) + '\n')

The repr function converts the row list into its string representation . repr函数将row列表转换为其字符串表示形式 The print calls that function internally, so you will have the same result that you otherwise observe on screen. print调用内部功能,因此您将获得与屏幕上观察到的相同的结果。

Try so, at me works: 试试吧,在我工作:

  with open(name) as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row) 

reference: 参考:

https://docs.python.org/3.6/library/csv.html#csv.DictReader https://docs.python.org/3.6/library/csv.html#csv.DictReader

maybe your scrollback buffer is just to short to see the whole list? 也许你的回滚缓冲区只是为了查看整个列表?

In general your csv.reader call should be working fine, except your 27k rows aren't extremly long so that you might be able to hit any 64bit boundaries, which would be quite uncommon. 一般来说,你的csv.reader调用应该工作正常,除了你的27k行不是很长,所以你可以打到任何64位边界,这是非常罕见的。

len(o) might be interesting to see. len(o)可能很有趣。

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

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