目前正在为专有文件格式进行EDI转换。输入文件可能有数百至数千条记录。每一行都是记录。
INFILE:(忽略起始空白行,它仅用于视觉表示)
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"我需要一个循环,可以逐行复制原始文件中某一列的数据,并将其粘贴到一个新文件中,该文件将数据保存在另一列中。有点像没有列标题的vlookup。这是列号之间的关系。
InColumn-OutColumn
1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 12-9, 14-10, 25-11, 68-24事先谢谢,我似乎不能把我的心思放在这件事上。
编辑:按照要求,这里是我无法工作的坏代码。
KEY = [1,2,3,4,5,6,7,8,12,14,25,68]
Body850 = open(TEMP, 'r+')
for line in Body850:
for x in line.split(','):
END += KEY[x]
print line发布于 2015-11-30 20:49:29
如前所述,csv模块可以处理引用的逗号。创建一个csv阅读器和一个作者,然后唯一的窍门是过滤列。
import csv
# todo: for testing...
open('testfile.csv', 'w').write('''"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"
"1","2","3","4","5","6","7","can also contain text, and commas","9","10","11","12","13"''')
# the columns wanted, in order they should appear in output (zero based)
# ...example doesn't go to 68 cols, so abreviated
column_order = (0,1,2,3,4,5,6,7,11)
with open('testfile.csv') as csvin:
reader = csv.reader(csvin)
with open('testfile_new.csv', 'w') as csvout:
writer = csv.writer(csvout)
for row in reader:
writer.writerow([row[i] for i in column_order])
# todo: for testing...
print(open('testfile_new.csv').read())发布于 2015-11-30 20:33:18
如果文本不包含引号,则可以:
for line in Body850:
for x in line.split('","'):
if x in KEY:
END += KEY[x]
else
pass # do something here in case x is not in KEY
print linehttps://stackoverflow.com/questions/34006549
复制相似问题