【发布时间】:2011-05-06 19:12:45
【问题描述】:
到目前为止,我有一个 Python 脚本可以完成我的工作...打开用户定义的 CSV,将文件拆分为不同的预定义“池”,然后将它们重新制作成自己的文件,并带有适当的标题。我唯一的问题是我想将池列表从静态更改为变量;并有一些问题。
池列表位于其自身的 CSV 中,在第 2 列中。并且可以复制。现在,通过此设置,系统可以创建除标题之外没有数据的“死”文件。
一些注意事项:是的,我知道拼写并不完美,是的,我知道我的一些 cmets 有点偏离
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')): line = line.split() x = 线[1] pools.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
【问题讨论】:
-
我建议您发布您的意图。看起来很复杂,可能您的意图可以通过简单的方式实现。我同意 SilentGhost 的观点。
-
dStulle 能够向我展示我需要做什么。谢谢!