简体   繁体   English

尝试读取CSV文件的第一行会返回['/']

[英]Trying to read the first line of CSV file returns ['/']

I have uploaded a CSV file through Django and I trying to read the first line of it. 我已经通过Django上传了一个CSV文件,并且尝试读取该文件的第一行。 The file is stored on the server in 该文件存储在服务器中

/tmp/csv_file/test.csv

The file looks like this: 该文件如下所示:

column_1,column_2,column_3
2175,294,Nuristan
2179,299,Sar-e-Pul

I am trying to get the headings of the file like: 我正在尝试获取文件的标题,例如:

absolute_base_file = '/tmp/csv_file/test.csv'
csv_reader = csv.reader(absolute_base_file)
csv_headings = next(csv_reader)
print csv_headings

I only get this in return: 我只能得到这个回报:

['/']

EDITED 已编辑

The permissions of the CSV file are: CSV文件的权限为:

-rw-rw-r--

Which should be ok. 哪个应该可以。

EDITED AGAIN 再次编辑

Based on the recommendations and the help of @EdChum and @Moses Koledoye 基于@EdChum和@Moses Koledoye的建议和帮助

I have checked if the file is read correctly using: 我使用以下方法检查了文件是否正确读取:

print (os.stat(absolute_base_file).st_size) # returns 64

Then I tried to see if seek(0) and csvfile.read(1) return a single printable character. 然后,我尝试查看seek(0)和csvfile.read(1)是否返回单个可打印字符。

   print csvfile.seek(0) returns None
   print csvfile.read(1) returns 'c'

Then I thought perhaps there is a particular issue with next() function and I tried an alternative: 然后我认为next()函数可能存在一个特定问题,因此尝试了另一种方法:

csv_reader = csv.reader(csvfile) 
for row in csv_reader:   
   print ("csv_reader") 

Again this didn't work. 再次,这没有用。

You passed a string instead of a file object which is why you get the slash, change to this: 您传递了字符串而不是文件对象,这就是为什么要得到斜线,请更改为:

with open (absolute_base_file) as csvfile:
    csv_reader = csv.reader(csvfile)

check the docs 检查文档

See this working: 看到这个工作:

In [5]:
import csv
with open (r'c:\data\csv_test.csv') as csvfile:
    csv_reader = csv.reader(csvfile)
    csv_headings = next(csv_reader)
    print (csv_headings)

['column_1', 'column_2', 'column_3']

To successively access each row call next : 要依次访问每个行调用next

In [7]:
import csv
with open (r'c:\data\csv_test.csv') as csvfile:
    csv_reader = csv.reader(csvfile)
    csv_headings = next(csv_reader)
    print (csv_headings)
    first_row = next(csv_reader)
    print( 'first row: ', first_row)


['column_1', 'column_2', 'column_3']
first row:  ['2175', '294', 'Nuristan']

You should pass a file object to your csv.reader not a string literal. 您应该将文件对象而不是字符串文字传递给csv.reader

absolute_base_file = open(r'/tmp/csv_file/test.csv') # notice open
csv_reader = csv.reader(absolute_base_file)
csv_headings = next(csv_reader)
print csv_headings

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

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