I open a file for appending:
file = open(filename, "a")
I have a numeric
CurrentCount=300
This 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
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:
Output:
intval: 300
reading result: 300
hexdump:
Output:
$ hd tryit.txt
00000000 33 30 30
00000003
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.
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 file
Sign of a true programmer!
I've been at it since 1968, and I can't count the number of times I did this.
(Apr-02-2019, 07:21 AM)sritaa Wrote: [ -> ]Read Only ('r') : Open text file for reading. ...
Read and Write ('r+') : Open the file for reading and writing. ...
Write Only ('w') : Open the file for writing. ...
Write and Read ('w+') : Open the file for reading and writing. ...
Append Only ('a') : Open the file for writing
Append and Read (‘a+’) : Open the file for reading and writing.
REDACTED
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.