Get values from a text file using Python
<p>I have some data in text file organized like this:</p>

<pre><code>26.11.2014  154601  26      53.07
16.12.2014  155001  25.2    52.1
</code></pre>

<p>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:</p>

<pre><code>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
</code></pre>

<p>I get data from user using:</p>

<pre><code>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]: "))
</code></pre>

<p>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 .</p>

<p>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 <code>benzyna.txt</code> file, removes the trailing newline and splits it based on <code>\t</code>. This creates a <code>data</code> 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:</p>

<pre><code>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 
</code></pre>

<p>This would display:</p>

<pre><code>[['26.11.2014', 154601.0, 26.0, 53.07], ['16.12.2014', 155001.0, 25.2, 52.1]]
</code></pre>

<hr>

<p>Alternatively, the following approach would also give you the same result:</p>

<pre><code>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
</code></pre>

python text-files