带有csv的Python:[Errno 2]没有这样的文件或目录

2024-10-17 08:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习“用Python自动化无聊的东西”, 这是书中的代码:

import csv, os

os.makedirs('headerRemoved', exist_ok=True)

#Loop through every file in the current working directory)

for csvFilename in os.listdir('C://Users//Xinxin//Desktop//123'):

    if not csvFilename.endswith('.csv'):
        continue # skip non-csv files

    print('Removing header from ' + csvFilename + '...')

    # Read the CSV file in (skipping first row).
    csvRows = []
    csvFileObj = open(csvFilename)
    readerObj = csv.reader(csvFileObj)
    for row in readerObj:
        if readerObj.line_num == 1:
            continue # skip first row
        csvRows.append(row)
    csvFileObj.close()

    # Write out the CSV file.
    csvFileObj = open(os.path.join('headerRemoved', csvFilename), 'w', newline='')
    csvWriter = csv.writer(csvFileObj)
    for row in csvRows:
        csvWriter.writerow(row)
    csvFileObj.close()

根据这本书,据说“在那个文件夹中运行上面的python程序” 它可以工作,但当我将python程序移出csv文件夹并运行代码时, 然后就显现出来了

C:\Users\Xinxin\PycharmProjects\PPPP\venv\Scripts\python.exe C:/Users/Xinxin/Desktop/removeheader.py
Removing header from NAICS_data_1048.csv...
Traceback (most recent call last):
  File "C:/Users/Xinxin/Desktop/removeheader.py", line 44, in <module>
    csvFileObj = open(csvFilename)
FileNotFoundError: [Errno 2] No such file or directory: 'NAICS_data_1048.csv'

Process finished with exit code 1

为什么csv文件无法打开?我已经在第4行写了绝对目录。。。 非常感谢您的帮助。


Tags: csvtheinforosopenusersfile
2条回答

but when I move the python program out of the csv folder, and run the code, then it shows

1)这就是问题所在。尝试将文件目录添加到removeheader.py(第一行):

import sys
sys.path.append(r'C:/Users/Xinxin/Desktop/123')

2)将文件存储在与脚本相同的位置,使您的生活更轻松

您需要获取当前目录。然后用文件名添加当前目录。 例如:

currentDir = os.getcwd()
currentFileCSV = currentDir +"//" + csvFilename
csvFileObj = open(currentFileCSV)

相关问题 更多 >