0
下列程序是用来读取一个CSV文件,并把它变成一个MySQL insert语句:IO错误没有这样的文件或目录,但文件不存在
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()
我甚至都没有想过这件事,你100%正确。谢谢您的帮助! – ThoseKind
不止欢迎@ThoseKind :) – AjahnCharles