我有一个小程序,只需要从csv文件中读取一行(而且只有一行),并将列值写入一系列文件。该程序有三个系统参数:数据文件的路径、作业id(uuid)和目标行号,即csv中要解析的行。它坏了,我怎么能修好它?在
import csv
import sys
import itertools
f = sys.argv[1]
uuid = sys.argv[2]
target_row = sys.argv[3]
tmpdir="/tmp/pagekicker/"
folder = tmpdir+uuid
destination1 = folder + '/csv/row.editedby'
destination3 = folder + '/csv/row.booktitle'
destination4 = folder + '/csv/row.seeds'
destination5 = folder + '/csv/row.imprint'
f = open(f, 'rb')
f1 = open(destination1, 'w')
f3 = open(destination3, 'w')
f4 = open(destination4, 'w')
f5 = open(destination5, 'w')
target_row = int(target_row)
try:
reader = csv.reader(f) # creates the reader object
for row in itertools.islice(reader,1,1): # iterates the rows of the file in orders
editedby = row[0] # we throw away column 2
booktitle = row[2]
print row[2]
seeds = row[3]
imprint = row[4]
f1.write(editedby)
f3.write(booktitle)
f4.write(seeds)
f5.write(imprint)
f.close()
f1.close()
f3.close()
f4.close()
f5.close()
finally:
print 'done'
更新:感谢格雷厄姆·贝尔推荐的代码。在他的'with'语句的第一行有两个“f5s”,我的代码现在是这样的:
我
^{pr2}$如果没有except,当我运行它时,它会生成“unexpected unident”。对于except,它表示except行是无效语法。在
假设您从1(而不是0)开始计算行数,下面是一个独立的函数来执行此操作:
csv library DictReader()对象能够显示当前行号:
您可以迭代,直到找到所需的正确行号,如下所示:
^{pr2}$DictReader类还允许您将CSV文件中的第一行作为标题列,然后可以按如下方式访问它们:
这可能也会为您节省一些工作,而且在处理以下文件时,您应该使用python with block:
这样你就不用担心把它们都关上了
相关问题 更多 >
编程相关推荐