2012-10-16 52 views
10

我是新来的编程在Python中,需要帮助做到这一点。从文本文件中读取多个数字

我有几个号码这样的文本文件:

12 35 21 
123 12 15 
12 18 89 

我需要能够读取每行的个体数能在数学公式来使用它们。

+0

'[图(浮动,LN .split())for ln in open(“filename”)if l.str()]' –

回答

9

在Python中,你从文件中读取一行作为字符串。然后,您可以使用字符串合作,以获得您需要的数据:

with open("datafile") as f: 
    for line in f: #Line is a string 
     #split the string on whitespace, return a list of numbers 
     # (as strings) 
     numbers_str = line.split() 
     #convert numbers to floats 
     numbers_float = [float(x) for x in numbers_str] #map(float,numbers_str) works too 

我所做的这一切在一堆的步骤,但你会经常看到有人将它们组合起来:

with open('datafile') as f: 
    for line in f: 
     numbers_float = map(float, line.split()) 
     #work with numbers_float here 

最后,在数学公式中使用它们也很容易。首先,创建一个功能:

def function(x,y,z): 
    return x+y+z 

现在通过你的文件重复调用该函数:

with open('datafile') as f: 
    for line in f: 
     numbers_float = map(float, line.split()) 
     print function(numbers_float[0],numbers_float[1],numbers_float[2]) 
     #shorthand: print function(*numbers_float) 
+0

这个工作很完美,谢谢 – slayeroffrog

6

另一种方式来做到这一点是通过使用numpy的函数调用loadtxt

import numpy as np 

data = np.loadtxt("datafile") 
first_row = data[:,0] 
second_row = data[:,1] 
0

这应该如果你命名你的文件numbers.txt工作

def get_numbers_from_file(file_name): 
    file = open(file_name, "r") 
    strnumbers = file.read().split() 
    return map(int, strnumbers) 


print get_numbers_from_file("numbers.txt") 

这必须在您发回[12,35,21,123,12,15,12,18,89] 可以选择individuly与list_variable [intergrer]每一个数字

0

下面的代码应该工作

f = open('somefile.txt','r') 
arrayList = [] 
for line in f.readlines(): 
    arrayList.extend(line.split()) 
f.close() 
0

如果你想在命令行中使用文件名作为参数,那么你就可以做到以下几点:

from sys import argv 

    input_file = argv[1] 
    with open(input_file,"r") as input_data: 
     A= [map(int,num.split()) for num in input_data.readlines()] 

    print A #read out your imported data 

否则,你可以这样做:

from os.path import dirname 

    with open(dirname(__file__) + '/filename.txt') as input_data: 
     A= [map(int,num.split()) for num in input_data.readlines()] 

    print A