我知道这是一个非常基本的问题。
我有一个CSV文件,其中已包含数据。此文件是自动生成的,不使用Dictreader
或打开对象打开。
任何线索?
cursor.execute(sql, params + (csv_path,))
此命令生成文件,没有标题。
sql, params = queryset.query.sql_with_params()
sql += ''' INTO OUTFILE %s
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n' '''
csv_path = os.path.join(settings.MEDIA_ROOT + '\\tmp', csv_filename)
cursor = connection.cursor()
cursor.execute(sql, params + (csv_path,))
columns = [column[0] for column in cursor.description] #error
SELECT `website` UNION SELECT `request_system_potentialcustomers`.`website` FROM `request_system_potentialcustomers` ORDER BY `request_system_potentialcustomers`.`revenue` DESC
INTO OUTFILE "D:\\out.csv"
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';
答案 0 :(得分:2)
等一下。如果你还没有打电话
cursor.execute(sql, params + (csv_path,))
然后您就有机会从一开始就正确地编写CSV文件。您不需要使用标题行编写新文件,然后将所有CSV复制到新文件中,依此类推。这是缓慢而低效的 - 而且是你唯一的选择 - 如果你真的必须在现有文件前加一行。
如果您还没有编写CSV文件,并且知道header
,那么您可以使用SELECT ... UNION ... SELECT
将其添加到SQL中:
header = ['foo', 'bar', 'baz', ]
query = ['SELECT {} UNION'.format(','.join([repr(h) for h in header]))]
sql, params = queryset.query.sql_with_params()
query.append(sql)
sql = '''INTO OUTFILE %s
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n' '''
query.append(sql)
sql = ' '.join(query)
csv_path = os.path.join(settings.MEDIA_ROOT + '\\tmp', csv_filename)
cursor = connection.cursor()
cursor.execute(sql, params + (csv_path,))
演示:
mysql> SELECT "foo", "bar" UNION SELECT "baz", "quux" INTO OUTFILE "/tmp/out";
生成包含
的文件/tmp/out
foo bar
baz quux
答案 1 :(得分:0)
Cursor.description
attribute为您提供有关结果列的信息。
cursor.execute(sql, params + (csv_path,))
columns = [column[0] for column in cursor.description]
答案 2 :(得分:0)
不是很清楚你是否试图读取现有的csv文件,而是读取没有列名的磁盘csv:
使用dictreader / dictwriter并在文件中指定列名
Python 3:
import csv
ordered_filenames = ['animal','height','weight']
with open('stuff.csv') as csvfile, open("result.csv","w",newline='') as result:
rdr = csv.DictReader(csvfile, fieldnames=ordered_filenames)
wtr = csv.DictWriter(result, ordered_filenames)
wtr.writeheader()
for line in rdr:
wtr.writerow(line)
将stuff.csv放在同一目录中:
elephant,1,200
cat,0.1,1
dog,0.2,2
和输出结果文件:
animal,height,weight
elephant,1,200
cat,0.1,1
dog,0.2,2