Python 使用 csv:[Errno 2] 没有这个文件或目录

3

我正在学习《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行写了绝对路径...... 非常感谢您的帮助。


它说文件不存在(或您的用户没有足够的权限) - Ramon Medeiros
您可以使用以下代码检查文件是否存在:os.path.exists() - Ramon Medeiros
为什么在'C://Users//Xinxin//Desktop//123'中要使用双斜杠? - Maximouse
@MaxiMouse 他本可以使用 r'C:/...'(基本上读作目录)或 'C://',这意味着如果“l/”或“n/”等是目录的一部分,则不需要转义行(例如 'C:/brown/stuff' 或 'C:/folder_name_ending_with_n/stuff','C:/full/stuff'' 或 'C:/folder_name_ending_with_l')。 - RealRageDontQuit
2个回答

4
但是当我将Python程序移出csv文件夹并运行代码后,它会显示以下错误: 1)这是问题所在。请在removeheader.py的第一行中添加文件目录:
import sys
sys.path.append(r'C:/Users/Xinxin/Desktop/123')

2) 把文件存储在与脚本相同的位置,这样可以让您的生活更加轻松。


1
我会提醒自己将脚本放到相同的位置,谢谢。 - Housoul

0
你可以获取当前目录。然后将当前目录和文件名相加。 例如:
currentDir = os.getcwd()
currentFileCSV = currentDir +"//" + csvFilename
csvFileObj = open(currentFileCSV)

是的,因为你只得到文件名,而没有得到文件的绝对路径。 - dohuuhung

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接