到目前为止,我有一个 Python 脚本可以完成我的任务...打开用户定义的 CSV,将文件拆分为不同的预定义“池”,然后将它们重新制作成自己的文件,并带有适当的标题。我唯一的问题是我想将 Pool 列表从静态更改为变量;并且有一些问题。
池列表位于 CSV 本身的第 2 列中,并且可以复制。现在使用此设置,系统可以创建“死”文件,除了标题之外没有任何数据。
一些注意事项:是的,我知道拼写并不完美,是的,我知道我的一些评论有点不对
import csv
#used to read ane make CSV's
import time
#used to timestamp files
import tkFileDialog
#used to allow user input
filename = tkFileDialog.askopenfilename(defaultextension = ".csv")
#Only user imput to locate the file it self
csvfile = []
#Declairs csvfile as a empty list
pools = ["1","2","4","6","9","A","B","D","E","F","I","K","L","M","N","O","P","W","Y"]
#declairs hte pools list for known pools
for i in pools:
#uses the Pools List and makes a large number of variables
exec("pool"+i+"=[]")
reader = csv.reader(open(filename, "rb"), delimiter = ',')
#Opens the CSV for the reader to use
for row in reader:
csvfile.append(row)
#dumps the CSV into a varilable
headers=[]
#declairs headers as empty list
headers.append(csvfile[0])
#appends the first row to the header variable
for row in csvfile:
pool = str(row[1]).capitalize()
#Checks to make sure all pools in the main data are capitalized
if pool in pools:
exec("pool"+pool+".append(row)")
#finds the pool list and appends the new item into the variable list
else:
pass
for i in pools:
exec("wp=csv.writer(open('pool "+i+" "+time.strftime("%Y%m%d")+".csv','wb'),)")
wp.writerows(headers)
#Adds the header row
exec("wp.writerows(pool"+i+")")
#Created the CSV with a timestamp useing the pool list
#-----Needs Headers writen in on each file -----
编辑: 由于有一些问题
代码的原因:我有正在生成的每日报告,其中需要手动处理的部分报告将这些报告拆分为不同的池报告。我正在创建这个脚本,以便我可以快速选择它自己的文件并将它们快速拆分成它们自己的文件。
主 CSV 的长度可以从 50 到 100 个项目,它总共有 25 列,并且池总是会列在第二列。并非所有池都会一直列出,并且池会出现多次。
到目前为止,我已经尝试了几个不同的循环;一个如下
池 = [] 对于文件中的行(打开(文件名,'rb')): 行 = 行.split() x = 行 [1] 池.append(x)
但是我得到一个列表错误。
CSV 示例:
Ticket Pool Date Column 4 Column 5
1 A 11/8/2010 etc etc
2 A 11/8/2010 etc etc
3 1 11/8/2010 etc etc
4 6 11/8/2010 etc etc
5 B 11/8/2010 etc etc
6 A 11/8/2010 etc etc
7 1 11/8/2010 etc etc
8 2 11/8/2010 etc etc
9 2 11/8/2010 etc etc
10 1 11/8/2010 etc etc
请您参考如下方法:
如果我没有正确理解您想在这里实现的目标,这可以作为解决方案:
import csv
import time
import tkFileDialog
filename = tkFileDialog.askopenfilename(defaultextension = ".csv")
reader = csv.reader(open(filename, "rb"), delimiter = ',')
headders = reader.next()
pool_dict = {}
for row in reader:
if not pool_dict.has_key(row[1]):
pool_dict[row[1]] = []
pool_dict[row[1]].append(row)
for key, val in pool_dict.items():
wp = csv.writer(open('pool ' +key+ ' '+time.strftime("%Y%m%d")+'.csv','wb'),)
wp.writerow(headders)
wp.writerows(val)
编辑:首先误解了 header 和池的事情,并试图纠正这个问题。
编辑 2:更正了从文件中找到的值动态创建的池。
如果不是,请提供您的问题的更多详细信息......
