[英]Get values from a text file using Python
I have some data in text file organized like this:我在文本文件中有一些数据是这样组织的:
26.11.2014 154601 26 53.07
16.12.2014 155001 25.2 52.1
Where first column is date, second kilometers, third fuel in litre and last is cost in polish zloty.第一列是日期,第二列是公里数,第三列是升燃料,最后一列是波兰兹罗提的成本。 I am trying create my personal program with refuelling statistics.
我正在尝试使用加油统计数据创建我的个人程序。 Here is the code where I save new data to the text file:
这是我将新数据保存到文本文件的代码:
def add_petrol_refueling(date, km, petrol_cost, petrol_volume):
plik = open('paliwo/benzyna.txt', 'a')
plik.write(date + '\t' + km + '\t' + petrol_cost + '\t' + petrol_volume)
plik.write('\n')
plik.close()
return True
I get data from user using:我使用以下方法从用户那里获取数据:
print add_petrol_refueling(raw_input("Refueling date [dd:mm:rrrr]: "),
raw_input("Kilometers on car screen [km]: "),
raw_input("Refueling cost [zł]: "),
raw_input("Refueling volume [l]: "))
And my question is How is the best option to get data from text file to do some operation with it and show later some statistics like average fuel consumption, average cost, when I can assume next refuelling etc .我的问题是如何从文本文件中获取数据以对其进行一些操作并稍后显示一些统计数据的最佳选择,例如平均油耗,平均成本,何时可以假设下一次加油等。
The following approach should help to get you started to get the data back from your text file.以下方法应该有助于您开始从文本文件中取回数据。 It first reads each line of your
benzyna.txt
file, removes the trailing newline and splits it based on \\t
.它首先读取您的
benzyna.txt
文件的每一行,删除尾随的换行符并根据\\t
将其拆分。 This creates a data
list containing 2 rows with 4 strings in each.这将创建一个包含 2 行、每行 4 个字符串的
data
列表。 Next it goes through each row and converts the last three entries from strings into floats so you can carry out your calculations on them:接下来它遍历每一行并将最后三个条目从字符串转换为浮点数,以便您可以对它们进行计算:
with open('benzyna.txt') as f_input:
data = [row.strip().split('\t') for row in f_input]
data = [[rdate, float(km), float(petrol_cost), float(petrol_vol)] for rdate, km, petrol_cost, petrol_vol in data]
print data
This would display:这将显示:
[['26.11.2014', 154601.0, 26.0, 53.07], ['16.12.2014', 155001.0, 25.2, 52.1]]
Alternatively, the following approach would also give you the same result:或者,以下方法也会为您提供相同的结果:
data = []
with open('benzyna.txt') as f_input:
for row in f_input:
rdate, km, petrol_cost, petrol_vol = row.strip().split('\t')
data.append([rdate, float(km), float(petrol_cost), float(petrol_vol)])
print data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.