![]() |
| Writing integer to file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Writing integer to file (/thread-17202.html) |
Writing integer to file - jpezz - Apr-02-2019 I open a file for appending: file = open(filename, "a")I have a numeric CurrentCount=300This prints 300 print (CurrentCount)This outputs a lot of digits, obviously not decoded into ASCII file.write(str(CurrentCount))What does? I want readable number in ASCII. I'm using Python 3.7 RE: Writing integer to file - Larz60+ - Apr-02-2019 You open the file as mode 'a' which means append. It will create the file if it doesn't exist, but if it does exist, it will retain contents and append new contents. you should open as mode 'w' if you don't want this. def write_file(filename, intval): with open(filename, 'w') as fp: print(f'intval: {intval}') fp.write(str(intval)) def read_file(filename): with open(filename) as fp: return fp.read() if __name__ == '__main__': myfile = 'tryit.txt' CurrentCount = 300 write_file(myfile, CurrentCount) print(f'reading result: {read_file(myfile)}')output:hexdump: RE: Writing integer to file - jpezz - Apr-02-2019 Yes! So stupid of me. In the actual code, the number was constantly changing so I didn't realize that what I was seeing was just multiple tries continuing on the same line. It hit me when I went to bed so I couldn't sleep and just after midnight I got up and just had to try a write instead of an append since all I wanted was a single line in the file. I was hoping I would solve my stupidity before someone else discovered it but you beat me to it. Thanks. RE: Writing integer to file - Larz60+ - Apr-02-2019 Quote:It hit me when I went to bed so I couldn't sleep and just after midnight I got up and just had to try a write instead of an append since all I wanted was a single line in the fileSign of a true programmer! I've been at it since 1968, and I can't count the number of times I did this. RE: Writing integer to file - jpezz - Apr-02-2019 (Apr-02-2019, 07:21 AM)sritaa Wrote: Read Only ('r') : Open text file for reading. ...Thanks. I know that - been using unix for 24 years. I originally meant to append the info to the file (but forgot that there was no newline in it so the append just added numbers to the same line. However, I figured out I dodn't need more than one piece of information and forgot to change the append to a write. |