I'm a beginner in Python, and I'm doing this project where I have a text file with 7 columns of numbers. 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. 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.
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:
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:
[['A', '3', '4'], ['D', '7', '8'], ['G', '0', '1']]
A solution that works with csv (or any delimited) file with any number of columns
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.