mysql
  • python-3.x
  • csv
  • ioerror
  • 2016-07-01 81 views 0 likes 
    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() 
    

    回答

    1

    绝对路径暗示我没有从该目录内运行脚本。

    我相信os.listdir只给你文件名而不是路径,这些文件名不存在于脚本运行的目录中。你需要连接路径和文件名!

    openFile = open(path + '/' + csvFile) 
    
    +0

    我甚至都没有想过这件事,你100%正确。谢谢您的帮助! – ThoseKind

    +0

    不止欢迎@ThoseKind :) – AjahnCharles

    相关问题