我正在学习《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行写了绝对路径...... 非常感谢您的帮助。
'C://Users//Xinxin//Desktop//123'
中要使用双斜杠? - Maximouse