简体   繁体   English

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

[英]parse txt file to 2 csv files

Hi I already have working code for parsing *.txt with such pattern: 嗨,我已经有使用以下模式解析*.txt工作代码:

...
0.00001
0.00280
0.00022
...

into *.csv file *.csv文件

I do it with this: 我这样做:

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()

I need help with modifying it to be able to parse the following pattern: 我需要修改它的帮助才能解析以下模式:

...
0.00001@0.02234
0.00280@0.00001
0.00022@0.03992
...

into 2 *.csv files (first with the first "column", second with the second "column") 放入2个* .csv文件(第一个带有第一个“列”,第二个带有第二个“列”)

A tested example: 经过测试的示例:

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)

here is a pandas approach which will work for any number of columns (just in case...): 这是一种熊猫方法,适用于任意数量的列(以防万一...):

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))

or as a one-liner (if you don't need to process your data): 或单行(如果您不需要处理数据):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM