简体   繁体   English

读取制表符分隔的txt文件并写入单独的列csv

[英]Read a tab delimited txt file and write to separate column csv

I have a txt file that have several lines for the headers which are represented by a '#'. 我有一个txt文件,标题有几行,用'#'表示。

Then I have three columns each with their own header that I want to copy into a csv file that will allow for each column to have their own column in the spreadsheet. 然后我有三个列,每个列都有自己的标题,我想将其复制到一个csv文件中,该文件允许每个列在电子表格中都有自己的列。

Currently all I am able to get is a file that has all three columns in one section of the csv. 目前,我所能获得的是一个在csv的一个部分中包含所有三列的文件。

import csv

infile = r'path\seawater_nh.txt'
outfile = r'path\emissivity_new.csv'

print "definitions successful"

in_txt = csv.reader(open(infile, 'rb'), delimiter = '\t')
out_csv = csv.writer(open(outfile, 'wb'))

out_csv.writerows(in_txt) 

In the absence of your sample input and output files, I'm guessing here. 在没有样本输入和输出文件的情况下,我猜这里。 But perhaps change how your files are read and written to (note: depending on the OS, you may need to change how the lines are read). 但也许会改变文件的读写方式(注意:根据操作系统的不同,您可能需要更改读取行的方式)。

import csv

infile = r'path\seawater_nh.txt'
outfile = r'path\emissivity_new.csv'

with open(infile, "r") as in_text:
    in_reader = csv.reader(infile , delimiter = '\t')
    with open(outfile, "w") as out_csv:
        out_writer = csv.writer(out_csv, newline='')
        for row in in_reader:
            out_writer.writerow(row)

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

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