09-第1步_循环遍历每个CSV文件
第1步:循环遍历每个CSV文件
程序需要做的第一件事情,就是循环遍历当前工作目录中所有CSV文件名的列表。让removeCsvHeader.py看起来像这样:
#! python3
# removeCsvHeader.py - Removes the header from all CSV files in the current
# working directory.
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
# Loop through every file in the current working directory.
for csvFilename in os.listdir('.'):
if not csvFilename.endswith('.csv'):
❶ continue # skip non-csv files
print('Removing header from ' + csvFilename + '...')
# TODO: Read the CSV file in (skipping first row).
# TODO: Write out the CSV file.
os.makedirs()
调用将创建 headerRemoved
文件夹,所有的无标题行的CSV文件将写入该文件夹。针对 os.listdir('.')
进行 for
循环完成了一部分任务,但这会遍历工作目录中的所有文件,因此需要在循环开始处添加一些代码,跳过扩展名不是.csv的文件。如果遇到非CSV文件, continue
语句❶让循环转向下一个文件名。
为了让程序运行时有一些输出,可以输出一条消息说明程序在处理哪个CSV文件。然后,添加一些TODO注释,说明程序的其余部分应该做什么。