首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python专有文件转换循环

Python专有文件转换循环
EN

Stack Overflow用户
提问于 2015-11-30 19:37:01
回答 2查看 116关注 0票数 0

目前正在为专有文件格式进行EDI转换。输入文件可能有数百至数千条记录。每一行都是记录。

INFILE:(忽略起始空白行,它仅用于视觉表示)

代码语言:javascript
复制
"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。这是列号之间的关系。

代码语言:javascript
复制
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

事先谢谢,我似乎不能把我的心思放在这件事上。

编辑:按照要求,这里是我无法工作的坏代码。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-30 20:49:29

如前所述,csv模块可以处理引用的逗号。创建一个csv阅读器和一个作者,然后唯一的窍门是过滤列。

代码语言:javascript
复制
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())
票数 1
EN

Stack Overflow用户

发布于 2015-11-30 20:33:18

如果文本不包含引号,则可以:

代码语言:javascript
复制
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 line
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34006549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档