【问题标题】:What is the easiest way to read the text file delimited by tab in python?在python中读取由制表符分隔的文本文件的最简单方法是什么?
【发布时间】:2013-06-12 01:51:42
【问题描述】:

在python中读取由制表符分隔的文本文件的最佳和最简单的方法是什么?我想将文本文件的第一列转换为转义第一行(标题)的列表。

import csv
with open ('data.txt', 'r') as f:
    first_row = [column[0] for column in csv.reader(f,delimiter='\t')]
    print (first_row)

上面的代码给出了 first_column 的所有元素。我怎样才能逃脱第一行(标题)?

【问题讨论】:

  • 将问题更改为不同的内容会使您已经接受的答案让其他读者感到困惑。以后我会建议创建一个新问题。
  • 好的,我已经提出了新问题,请帮忙。

标签: python python-2.7 python-3.x


【解决方案1】:

也许我在问题中遗漏了一些东西,但为什么不直接切掉列表的第一个元素呢?

import csv
with open ('data.txt', 'r') as f:
    first_column = [row[0] for row in csv.reader(f,delimiter='\t')]
    print (first_column[1:])

【讨论】:

    【解决方案2】:

    加载文件后,您可以按列名访问数据。在此示例中,FirstColName 是已加载文件的第一列名称。

    import pandas as pd
    import numpy as np
    
    file = pd.read_csv(r"C:\Users\hydro\a.txt", sep='\t')
    firstCol = np.asarray(file.FirstColName)
    print (firstCol)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2011-03-25
      • 2011-01-05
      • 1970-01-01
      相关资源
      最近更新 更多