我是新來的編程在Python中,需要幫助做到這一點。從文本文件中讀取多個數字
我有幾個號碼這樣的文本文件:
12 35 21
123 12 15
12 18 89
我需要能夠讀取每行的個體數能在數學公式來使用它們。
我是新來的編程在Python中,需要幫助做到這一點。從文本文件中讀取多個數字
我有幾個號碼這樣的文本文件:
12 35 21
123 12 15
12 18 89
我需要能夠讀取每行的個體數能在數學公式來使用它們。
在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)
這個工作很完美,謝謝 – slayeroffrog
另一種方式來做到這一點是通過使用numpy
的函數調用loadtxt
。
import numpy as np
data = np.loadtxt("datafile")
first_row = data[:,0]
second_row = data[:,1]
這應該如果你命名你的文件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]每一個數字
下面的代碼應該工作
f = open('somefile.txt','r')
arrayList = []
for line in f.readlines():
arrayList.extend(line.split())
f.close()
如果你想在命令行中使用文件名作爲參數,那麼你就可以做到以下幾點:
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
'[圖(浮動,LN .split())for ln in open(「filename」)if l.str()]' –