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

4

1 回答 1

2

传递inplace=1fileinput.input()修改文件的地方。循环内打印的所有内容都将写入文件:

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

如果input.txt包含:

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

代码将打印:

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

的内容input.txt变为:

1 2 0
1 3 0
于 2014-04-02T16:16:27.200 回答