16.Python读取多个格式相同的文件(多个csv文件)

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) 返回文件名称。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值