[英]Extract rows and save to multiple csv files
I am trying to solve the following problem using Python: I've a table (csv) from which I want to extract consecutively row 1 + 2, then row 1 + 3, then row 1 + 4, etc. The extracts should be saved again as csv file and named according to the first string in the 2nd row to be extracted (2, 3, 4, 5,...). 我正在尝试使用Python解决以下问题:我有一张表(csv),我要从中连续提取第1 + 2行,然后是第1 + 3行,然后是第1 + 4行,依此类推。应保存提取内容再次作为csv文件,并根据要提取的第二行中的第一个字符串命名(2、3、4、5,...)。 Now my question - is python the right tool to do this and is there any example code available?
现在我的问题-python是执行此操作的正确工具,并且有可用的示例代码吗?
Thanks a lot in advance for any help & hints! 在此先非常感谢您的帮助和提示!
Claude S. 克劳德·S。
Thanks for the feedback - actually I was trying to use the csv module to open and read the table using this code: 感谢您的反馈-实际上,我尝试使用csv模块使用以下代码打开和读取表:
import csv
import sys
f = open(sys.argv[1], 'rt')
try:
reader = csv.reader(f)
for row in reader:
print row
Now I am not sure how to select and write the required rows... sorry for the beginners kind of question. 现在,我不确定如何选择和写入所需的行...对于初学者来说,这很抱歉。 Claude S.
克劳德·S。
fname = argv[1]
with open(fname) as i:
reader = csv.reader(i)
first_row = next(reader)
for cur_row in reader:
out_name = cur_row[0]
with open(out_name, 'wb') as o:
writer = csv.writer(o)
writer.writerow(first_row)
writer.writerow(cur_row)
Hope it helps 希望能帮助到你
I'm not convinced that you need the csv module (unless the first column could contain quotes and commas). 我不认为您需要csv模块(除非第一列可以包含引号和逗号)。 If your file format is simple, just use split.
如果您的文件格式很简单,请使用split。
fname = argv[1]
with open(fname) as f:
header = f.readline()
# parse the rest of the lines.
for line in f:
out_name = line.split(',')[0]
with open(out_name, 'wb') as o:
o.write(header)
o.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.