'Python with csv: [Errno 2] No such file or directory

I am learning 'Automate the Boring Stuff with Python', here is the code in the book:

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()

According to the book, it is said 'Run the above python program in that folder.' It works, but when I move the python program out of the csv folder, and run the code, then it shows

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

Why csv files cnannot open? I already wrote absolute dir in line4... Thank you so much for your help.



Solution 1:[1]

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

1) This is the problem. Try adding the directory of the files to your removeheader.py (first line):

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

2) Store the files in the same location as the script to make your life easier

Solution 2:[2]

You can need get current directory. Then add current directory with file name. Example:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RealRageDontQuit
Solution 2 dohuuhung