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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With