【问题标题】:IOError No such file or directory, but file does existIOError 没有这样的文件或目录,但文件确实存在
【发布时间】: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


    【解决方案1】:

    绝对路径向我表明您没有从该目录中运行脚本。

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

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

    【讨论】:

    • 我什至没有想到,你是 100% 正确的。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多