【问题标题】:Read and export a single column from a tab-separated file in Python在 Python 中从制表符分隔的文件中读取和导出单个列
【发布时间】:2016-01-17 23:15:21
【问题描述】:

我有许多以制表符分隔的大文件保存为.txt,每个文件有七列,标题如下:

#column_titles = ["col1", "col2", "col3", "col4", "col5", "col6", "text"]    

我想简单地提取名为text 的最后一列并将其保存到一个新文件中,每一行都是原始文件中的一行,而都是字符串。

编辑:这不是 a similar problem 的副本,因为在我的情况下 splitlines() 不是必需的。只有事情的顺序需要改进

基于 -several - other - posts,这是我目前的尝试:

import csv

# File names: to read in from and read out to
input_file = "tester_2014-10-30_til_2014-08-01.txt"
output_file = input_file + "-SA_input.txt"

## ==================== ##
##  Using module 'csv'  ##
## ==================== ##
with open(input_file) as to_read:
    reader = csv.reader(to_read, delimiter = "\t")

    desired_column = [6]        # text column

    for row in reader:
    myColumn = list(row[i] for i in desired_column)

with open(output_file, "wb") as tmp_file:
    writer = csv.writer(tmp_file)

for row in myColumn:
    writer.writerow(row)

我得到的只是输入文件中第 2624 行的文本字段,该字符串中的每个字母都被分离出来:

H,o,w, ,t,h,e, ,t.e.a.m, ,d,i,d, ,T,h,u,r,s,d,a,y, ,-, ,s,e,e , ,h,e,r,e

我对编程世界知之甚少是随机的,但这绝对是奇怪的!

This post 与我的需求非常相似,但缺少写入和保存部分,我也不确定。

我已经研究过使用 pandas 工具箱(根据上述链接之一),但我无法安装 Python,因此请仅使用 csv 或其他内置模块的解决方案!

【问题讨论】:

标签: python csv


【解决方案1】:

我会选择这个简单的解决方案:

    text_strings = [] # empty array to store the last column text
    with open('my_file') as ff:
        ss = ff.readlines() # read all strings in a string array 

    for s in ss:
        text_strings.append(s.split('\t')[-1]) # last column to the text array



    with open('out_file') as outf:
        outf.write('\n'.join(text_strings)) # write everything to output file

使用列表推导,您可以在一行中更快地将ss 字符串的最后一列转换为text_strings

    text_strings = [k.split("\t")[-1] for k in ss]

还有其他可能的简化,你懂的)

代码中的问题出现在这两行:

        for row in reader:
        myColumn = list(row[i] for i in desired_column)

首先,没有缩进,所以什么也没有发生。实际上,在我的电脑上,它会抛出一个错误,所以它有可能是一个错字。但是在这种情况下,在 for 循环的每个步骤中,您都会用来自新行的值覆盖 myColumn 值,因此最后您会得到文件最后一行的字符串。 其次,list 应用于字符串(如您的代码中所示),将字符串转换为字符列表:

    In [5]: s = 'AAAA'

    In [6]: list(s)
    Out[6]: ['A', 'A', 'A', 'A']

这正是您在输出中看到的。

【讨论】:

  • 嗯,使用该示例输入它可以工作,但 csv 文件可能要复杂得多。您将如何处理逗号 (,) 或双引号中的换行符? csv 模块之所以存在是因为它正确处理了所有极端情况
  • @pausag - 缩进错误来自我错误的代码复制/粘贴 - 它不在我的文件中。你的例子对我不起作用,抛出错误:**ff.write('\n'.join(text_strings)) # write everything to output file ValueError: I/O operation on closed file**
  • @SergeBallesta 好点,对于 csv 输入,当然应该考虑这些。然而,给定的问题是说有“大的 txt 制表符分隔文件”,所以我看不到在这里使用 csv 的意义。顺便说一句,我也没有注意到问题中的制表符分隔符。编辑答案。
  • @DexterMorgan,你在写,这是我的错字。应该有outf.write(...),而不是ff。编辑了帖子
  • 我确实将您的逗号编辑为\t,但我仍然遇到与以前相同的错误。 Serge 的回答已被接受,但感谢您教我一些关于readlines() 的新知识!
【解决方案2】:

您必须一次处理一行文件:读取、解析和写入。

import csv

# File names: to read in from and read out to
input_file = "tester_2014-10-30_til_2014-08-01.txt"
output_file = input_file + "-SA_input.txt"

## ==================== ##
##  Using module 'csv'  ##
## ==================== ##
with open(input_file) as to_read:
    with open(output_file, "wb") as tmp_file:
        reader = csv.reader(to_read, delimiter = "\t")
        writer = csv.writer(tmp_file)

        desired_column = [6]        # text column

        for row in reader:     # read one row at a time
            myColumn = list(row[i] for i in desired_column)   # build the output row (process)
            writer.writerow(myColumn) # write it

【讨论】:

  • 谢谢美女!无需我改变任何东西就可以工作。我那里有所有正确的成分,只是我脑子里的食谱是错误的。
  • 您介意编辑您的代码以突出显示“读取、解析、写入”步骤发生的确切位置吗?
猜你喜欢
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
相关资源
最近更新 更多