Store data as numbers in a file in Python
Question: I wrote a program that opens a file and read it line by line and store just
the third element of each line. The problem is that, when I write those
outputs into a file I need to change them as strings which is not suitable for
me due to the fact that I want to do some mathematical operations on the
written file later on. FYI, it also is not suitable to store it like this and
use int() while reading it.

Can anybody help me with this issue?

    
    
    with open("/home/test1_to_write", "w") as g:
        with open("/home/test1_to_read", 'r') as f:
            for line in f:
                a=line.split()
                number = int(a[3])
                g.write(str(number)+'\n')
    
    g.close()
    


Answer: There's no way to tell a text file that `1` is the number one not the letter
`"1"`. If you need that, consider storing the whole thing as a list instead
using some sort of serial format e.g. JSON:

    
    
    import json
    
    with open("/home/test1_to_write.json", 'w') as outfile:
        with open("/home/test1_to_read", 'r') as infile:
            data = [int(line.split()[3]) for line in infile]
            json.dump(data, outfile)
    

You can then load the data with:

    
    
    with open("/home/test1_to_write.json", "r") as infile:
        read_data = json.load(infile)
    

