python练习项目九——从CSV 文件中删除表头
项目:从CSV 文件中删除表头
背景
假设你有一个枯燥的任务,要删除几百CSV 文件的第一行。也许你会将它们送入一个自动化的过程,只需要数据,不需要每列顶部的表头。可以在Excel 中打开每个文件,删除第一行,并重新保存该文件,但这需要几个小时。让我们写一个程序来做这件事。该程序需要打开当前工作目录中所有扩展名为.csv 的文件,读取CSV 文件的内容,并除掉第一行的内容重新写入同名的文件。这将用新的、无表头的内容替换CSV 文件的旧内容。
注:与往常一样,当你写程序修改文件时,一定要先备份这些文件,以防万一你的程序没有按期望的方式工作。你不希望意外地删除原始文件。
练习内容
①csv.reader()
Reader 对象 用csv 模块从CSV 文件中读取数据,需要创建一个Reader 对象。Reader 对象让你迭代遍历CSV 文件中的每一行。 首先用open()函数打开它,就像打开任何其他文本文件一样。但是,不用在open()返回的File 对象上调用read()或readlines()方法,而是将它传递给csv.reader()函数。这将返回一个Reader 对象,供使用。 ②在for 循环中,从Reader 对象读取数据 ③csv.writer() 在Windows 上,需要为open()函数的newline 关键字参数传入一个空字符串。这样做的技术原因超出了本书的范围。如果忘记设置newline 关键字参数,output.csv中的行距将有两倍。
参考思路
总的来说,该程序必须做到以下几点:
-
找出当前工作目录中的所有CSV 文件。 读取每个文件的全部内容。 跳过第一行,将内容写入一个新的CSV 文件。
在代码层面上,这意味着该程序需要做到以下几点: ①循环遍历从os.listdir()得到的文件列表,跳过非CSV 文件。 ②创建一个CSV Reader 对象,读取该文件的内容,利用line_num 属性确定要跳过哪一行。 ③创建一个CSV Writer 对象,将读入的数据写入新文件。
代码实现:
#! 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 + ...) # 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()