我已经通过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
我只得到这个回报:
['/']
EDITED
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")
这再次没有用。
答案 0 :(得分:3)
你传递了一个字符串而不是一个文件对象,这就是你得到斜杠的原因,改为:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
检查docs
看到这个工作:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
要连续访问每一行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']
答案 1 :(得分:1)
您应该将文件对象传递给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