gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:08 25 4
gpt4 key购买 nike

我已经通过 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)

检查docs

看到这个工作:

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

关于python - 尝试读取 CSV 文件的第一行返回 ['/'],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com