【发布时间】:2016-07-01 22:18:43
【问题描述】:
下面的程序用来读取一个CSV文件,并把它变成一个MySQL的插入语句:
import csv
openFile = open('test.csv', 'r')
csvFile = csv.reader(openFile)
header = next(csvFile)
headers = map((lambda x: "'"+x+"'"), header)
insert = 'INSERT INTO Table (' + ", ".join(headers) +", 'time_stamp'" +") VALUES "
for row in csvFile:
values = map((lambda x: "'"+x.strip()+"'"), row)
print (insert +"("+ ", ".join(values) +", getdate());" )
openFile.close()
我进行了以下修改,试图让程序处理多个文件,而不是仅仅明确列出文件名,但当文件明显存在时不断收到错误消息 IOError: [Errno 2] No such file or directory: 'Exact name of existing file.csv',因为它正在打印确切的文件名.如何编辑以下代码以使其适用于目录中的一组文件而不会出现上述错误?
import csv, os
path = 'C:/Users/August/Desktop/TripDetailFiles/test'
for csvFile in os.listdir(path):
if csvFile.endswith('.csv'):
openFile = open(csvFile)
readFile = csv.reader(openFile)
header = next(readFile)
headers = map((lambda x: "'"+x+"'"), header)
insert = 'INSERT INTO Table (' + ", ".join(headers) +", 'time_stamp'" +") VALUES "
for row in csvFile:
values = map((lambda x: "'"+x.strip()+"'"), row)
print (insert +"("+ ", ".join(values) +", getdate());" )
openFile.close()
【问题讨论】:
标签: mysql python-3.x csv ioerror