1

Hi please how can I loop over a text file, identify lines with 0s at the last index of such a line, and delete those lines while retrieving the ones not deleted. Then also format the output to be tuples.

input.txt = 1 2 0 
            1 3 0 
            11 4 0.058529
            ...
            ...
            ...
            97 7 0.0789

Desired output should look like this

[(11,4,{'volume': 0.058529})]

Thank you

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Did u try something? may be regular expressions? – Arvind Apr 02 '14 at 16:11
  • I'd use the [csv module](https://docs.python.org/2/library/csv.html) to read the input, slices `[:-1]` and `[-1]` to split the last value, and [string `format`](https://docs.python.org/2/library/string.html#string-formatting) to create the output. – Mark Ransom Apr 02 '14 at 16:13

1 Answers1

2

Pass inplace=1 to the fileinput.input() to modify the file in place. Everything that is printed inside the loop is written to the file:

import fileinput

results = []
for line in fileinput.input('input.txt', inplace=1):
    data = line.split()
    if data[-1].strip() == '0':
        print line.strip()
    else:
        results.append(tuple(map(int, data[:-1])) + ({'volume': float(data[-1])}, ))

print results

If the input.txt contains:

1 2 0
1 3 0
11 4 0.058529
97 7 0.0789

the code will print:

[(11, 4, {'volume': 0.058529}), 
 (97, 7, {'volume': 0.0789})]

And the contents of the input.txt becomes:

1 2 0
1 3 0
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195