简体   繁体   English

使用python读取txt文件中的列表

[英]Using python to read a list in a txt file

I'm a beginner in Python, and I'm doing this project where I have a text file with 7 columns of numbers. 我是Python的初学者,我正在做这个项目,我有一个包含7列数字的文本文件。 I need to write a program that extracts the data for columns 1, 6, and 7, and prints them out in columns with just those data in columns alone. 我需要编写一个程序来提取第1列,第6列和第7列的数据,然后将它们打印在列中,仅列中的数据。 This is what I have done so far, but something seems to be wrong. 这是我到目前为止所做的,但似乎有些不对劲。 Can someone point me out? 有人能指出我吗?

import sys
import os
import re

GC11 = 'NGC4697'

base_dirname = '/projects/XRB_Web/abcadmus/499/Lists/'
Luminositylist = base_dirname + GC11 + '_final_list.txt'

try:
  file = open(Luminositylist, 'r')
except IOError:
  print 'Cannot open: '+Luminositylist

source = [ ]
luminosity = [ ]
luminosityerr = [ ]
for line in file:
   point = line.split()
   a = source.append(int((point[0])))
   b = luminosity.append(float((point[5])))
   c = luminosityerr.append(float((point[6])))
   print a, b, c

list.append() returns None , so your assignments aren't doing anything useful. list.append()返回None ,因此您的赋值没有做任何有用的事情。

I'm not sure why you need to print them and append them to a list, but try this instead: 我不确定为什么你需要打印它们并将它们附加到列表中,但请尝试这样做:

   point = line.split()

   a = int(point[0])
   b = float(point[5])
   c = float(point[6])

   source.append(a)
   luminosity.append(b)
   luminosityerr.append(c)

   print a, b, c

看一下Python CSV库: http//docs.python.org/2/library/csv.html ,您可能会发现它已经完成了您所需要的一切。

Assuming I have a file named test.txt with the following layout: 假设我有一个名为test.txt的文件,其格式如下:

ABC1234
DEF5678
GHI9101

I can do this, 我可以做这个,

with open('test.txt', 'r') as f:
  out = [[x[0],x[5],x[6]] for x in f.readlines()]

To get a result in out that looks like this: 为了得到一个结果out ,看起来像这样:

[['A', '3', '4'], ['D', '7', '8'], ['G', '0', '1']]

A solution that works with csv (or any delimited) file with any number of columns 适用于具有任意数量列的csv(或任何分隔)文件的解决方案

f = file("myFile", mode="r")
delimiter = "," # comma for csv files

myData = [i.split(delimiter) for i in file.readlines()] # All the data as a nested list
myColumns = [row[0],row[5],row[6] for row in myData] # select your source, lum and lumerr columns
source, luminosity, luminosityerr = zip(*myColumns)

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

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