簡體   English   中英

嘗試讀取CSV文件的第一行會返回['/']

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

我已經通過Django上傳了一個CSV文件,並且嘗試讀取該文件的第一行。 該文件存儲在服務器中

/tmp/csv_file/test.csv

該文件如下所示:

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

我正在嘗試獲取文件的標題,例如:

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

我只能得到這個回報:

['/']

已編輯

CSV文件的權限為:

-rw-rw-r--

哪個應該可以。

再次編輯

基於@EdChum和@Moses Koledoye的建議和幫助

我使用以下方法檢查了文件是否正確讀取:

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

然后,我嘗試查看seek(0)和csvfile.read(1)是否返回單個可打印字符。

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

然后我認為next()函數可能存在一個特定問題,因此嘗試了另一種方法:

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

再次,這沒有用。

您傳遞了字符串而不是文件對象,這就是為什么要得到斜線,請更改為:

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

檢查文檔

看到這個工作:

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']

要依次訪問每個行調用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']

您應該將文件對象而不是字符串文字傳遞給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