简体   繁体   中英

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 . This creates a data list containing 2 rows with 4 strings in each. 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

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.

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