Python使用两列将文本写入CSV

时间:2013-10-30 17:09:04

标签: python csv

嗨,我这里有一个小问题。

我有一个带有数字的文本文件,看起来像这样

2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990

并且

fList = [s.strip() for s in open('out.txt').readlines()]
outStr = ''
for i in fList:
      outStr += (i+',')
f = open('text_to_csv.csv', 'w')
f.write(outStr.strip())
f.close()

我能够生成CSV并且所有数据都存储在其中,但所有数据都存储在一行中。 我想将它们分为两列。

是否有任何简单的添加可以使CSV看起来像这样?

2.131583 2.058964
6.866568 0.996470
6.424396 0.996004

6 个答案:

答案 0 :(得分:2)

更好的方法是使用csv模块。你可以这样写

import csv

with open('text_to_csv.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',quoting=csv.QUOTE_MINIMAL)
    for i in range(0, len(fList), 2):
        writer.writerow(fList[i:i+2])

答案 1 :(得分:1)

fList = [s.strip() for s in open('out.txt').readlines()]
outStr = ''
count = 0
for i in fList:
      outStr += (i+',')
      if count % 2 == 0: # You can replace 2 with what ever number you of columns you need
          outStr += ('\r\n') # Make the return correct for your system
      count += 1
f = open('text_to_csv.csv', 'w')
f.write(outStr.strip())
f.close()

答案 2 :(得分:0)

如果您在内存中有一个列表(来自阅读文件),只需将列表重新格式化为您想要的内容:

input='''\
2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990'''    

cols=2

data=input.split()       # proxy for a file
print data
print '==='
for li in [data[i:i+cols] for i in range(0,len(data),cols)]:
    print li

打印:

['2.131583', '2.058964', '6.866568', '0.996470', '6.424396', '0.996004', '6.421990']
===
['2.131583', '2.058964']
['6.866568', '0.996470']
['6.424396', '0.996004']
['6.421990']

或者,使用N-at-time-file读取习语:

import itertools
cols=2
with open('/tmp/nums.txt') as fin:
    for li in itertools.izip_longest(*[fin]*cols):
        print li  
# prints
('2.131583\n', '2.058964\n')
('6.866568\n', '0.996470\n')
('6.424396\n', '0.996004\n')
('6.421990', None)

如果你想要一种文件过滤器,可以组合成一个迭代器,一个迭代器:

import itertools
cols=2
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
    for li in itertools.izip_longest(*[fin]*cols):
        fout.write('\t'.join(e.strip() for e in li if e)+'\n')

输出文件现在为:

2.131583    2.058964
6.866568    0.996470
6.424396    0.996004
6.421990

如果你只想写输出,那么就有一整套数字,即文件末尾的余数小于总长度的cols

import itertools
cols=2
# last number '6.421990' not included since izip is used instead of izip_longest
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
    for li in itertools.izip(*[fin]*cols):
        fout.write('\t'.join(e.strip() for e in li)+'\n') 

然后输出文件是:

2.131583    2.058964
6.866568    0.996470
6.424396    0.996004

答案 3 :(得分:0)

这样的事情:

with open('out.txt', 'r') as fList, open('text_to_csv.csv', 'w') as f:
    i = 0
    for line in fList:
        f.write(line)
        f.write('\n' if i% 2 == 0 else '\t')`

答案 4 :(得分:0)

如果您不想将原始文件中的条目存储在新列表中但只想要输出文件,您还可以执行以下操作:

fList = [s.strip() for s in open('out.txt').readlines()]
f = open('text_to_csv.csv', 'w')
for i in range(0,len(fList)-1,2):
    f.write(fList[i] + "," + fList[i+1] + "\n")

f.close()

答案 5 :(得分:0)

我不太确定你的意思,但我认为你的预期输出是:

2.131583,2.058964,
6.866568,0.996470,
6.424396,0.996004,
6.421990

我的代码:

with open('out.txt', 'r') as fif, open('text_to_csv.csv', 'w') as fof:
    fList = ','.join([v.strip() if i % 2 else '\n'+v.strip()
                      for i, v in enumerate(fif.readlines())])[1:]
    fof.write(fList)


有趣的观点:

如果你想摆脱文件末尾的“,”,只需通过join()函数连接列表。

flat_string = ','.join([item1,...,])

对于列表中奇数项的引导换行符,我已经枚举了它。

index, value enumerate([item1,...,])

通过模运算符index % 2找到奇数项。

使用“inline-if”,您可以即时查看。

至少我在[1:]

字符串的开头排除了冗余换行符