pythonfilepython-2.7file-ioinplace-editing

Formatting files to be written


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


Solution

  • 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