将txt文件解析为2个csv文件

时间:2016-06-27 20:33:18

标签: python csv parsing pandas

您好我已经有了使用这种模式解析# flattened.push *(element.is_a?(Array) ? flattify(element) : element) # flattened is the array ...object([]) # element.is_a?(Array) ...is the element in this iteration an array? # if true flattify(element) again... meaning recursively apply method again # if false push element onto the object([]) aka flattened # the () around the ternary allow the recursion to complete # the * operator can then pass the elements "passing the array condition" # cont'd... onto flattened.push(4, 5, 6) as list of args instead of an array # array object with range of string elements ("a".."c").each_with_object([]) do |element, the_object| p the_object.class # returns Array p element.class # returns String end # hash object with range of fixnum elements (1..3).each_with_object({}) do |element, the_object| p the_object.class # returns Hash p element.class # returns Fixnum end 的工作代码:

*.txt

进入... 0.00001 0.00280 0.00022 ... 档案

我这样做:

*.csv

我需要帮助修改它才能解析以下模式:

in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\n')
f = open(csv_file, 'wb')
out_csv = csv.writer(f)
out_csv.writerows(in_txt)
f.close()

分为2 * .csv文件(首先是第一个“列”,第二个是第二个“列”)

2 个答案:

答案 0 :(得分:1)

经过测试的例子:

import csv, os

txt_file = '/path/to/in.txt'
in_txt = csv.reader(open(txt_file, 'rb'), delimiter='@')
out_file1 = '/path/to/out1.txt'
out_file2 = '/path/to/out2.txt'
with open(out_file1, 'wb') as fou1, open(out_file2, 'wb') as fou2:
    for one, two in in_txt:
        fou1.write(one + os.linesep)
        fou2.write(two + os.linesep)

答案 1 :(得分:1)

这是一个pandas方法,适用于任意数量的列(以防万一......):

import pandas as pd

in_fn = '/path/to/in.csv'
out_fn_pattern = '/path/to/out_{}.csv'

# parse CSV to DataFrame
df = pd.read_csv(in_fn, sep='@', header=None)
# save each column in a separate CSV file
df.apply(lambda x: x.to_csv(out_fn_pattern.format(x.name), header=None, index=False))

或作为单行(如果您不需要处理数据):

(pd.read_csv(in_fn, sep='@', header=None)
   .apply(lambda x: x.to_csv(out_fn_pattern.format(x.name),
                             header=None, index=False))
)