1.文件准备
more sales_jannary_2014.csv
Customer ID,Customer Name,Invoice Number,Sale Amount,Purchase Date
1234,John Smith,100-0002,"$1,200.00 ",1/1/2014
2345,Mary Harrison,100-0003,"$1,425.00 ",1/6/2014
3456,Lucy Gomez,100-0004,"$1,390.00 ",1/11/2014
4567,Rupert Jones,100-0005,"$1,257.00 ",1/18/2014
5678,Jenny Walters,100-0006,"$1,725.00 ",1/24/2014
6789,Samantha Donadson,100-0007,"$1,995.00 ",1/31/2014
more sales_february_2014.csv
Customer ID,Customer Name,Invoice Number,Sale Amount,Purchase Date
9876,Danniel Farber,100-0008,"$1,115.00 ",2/2/2014
8765,Laney Stone,100-0009,"$1,367.00 ",2/8/2014
7654,Roger Lipney,100-0010,"$2,135.00 ",2/15/2014
6543,Thomas Haines,100-0011,"$1,346.00 ",2/17/2014
5432,Anushka Vaz,100-0012,"$1,560.00 ",2/21/2014
4321,Harriet Cooper,100-0013,"$1,852.00 ",2/25/2014
more sales_march_2014.csv
Customer ID,Customer Name,Invoice Number,Sale Amount,Purchase Date
1234,John Smith,100-0014,"$1,350.00 ",3/4/2014
8765,Tonny Song,100-0015,"$1,167.00 ",3/8/2014
2345,Mary Harrison,100-0016,"$1,789.00 ",3/17/2014
6543,Rachel Paz,100-0017,"$2,042.00 ",3/22/2014
3456,Lucy Gomez,100-0018,"$1,511.00 ",3/28/2014
4321,Susan Wallace,100-0019,"$2,280.00 ",3/30/2014
2.文件计数与文件中的行列计数
vi 8csv_reader_counts_for_multiple_files.py
#!/usr/bin/env python3
import csv
import glob
import os
import sys
input_path=sys.argv[1]
file_couter=0
for input_file in glob.glob(os.path.join(input_path,'sales_*')):
row_counter=1
with open(input_file,'rb') as csv_in_file:
filereader=csv.reader(csv_in_file)
header=next(filereader,None)
for row in filereader:
row_counter+=1
print('{0!s}:\t{1:d} \t{2:d} columns'.format(os.path.basename(input_file),row_counter,len(header)))
file_couter+=1
print('Number of files:{0:d}'.format(file_couter))
#结果
[root@mysql51 python_scripts]# python 8csv_reader_counts_for_multiple_files.py /root/python_scripts
sales_march_2014.csv: 7 5 columns
sales_jannary_2014.csv: 7 5 columns
sales_february_2014.csv: 7 5 columns
Number of files:3
3.总结
os.path.join 的结果是csv文件的列表。
glob.glob()函数将sales_*的模糊匹配转换为实际的名字。
os.path.basename(input_file) 返回文件名称。