Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing integer to file
#2
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
Reply


Messages In This Thread
Writing integer to file - by jpezz - Apr-02-2019, 01:57 AM
RE: Writing integer to file - by Larz60+ - Apr-02-2019, 02:37 AM
RE: Writing integer to file - by jpezz - Apr-02-2019, 04:38 AM
RE: Writing integer to file - by Larz60+ - Apr-02-2019, 09:06 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  writing list to csv file problem jacksfrustration 3 134 4 hours ago
Last Post: deanhystad
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,620 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,115 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,814 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Writing to file ends incorrectly project_science 4 2,928 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 5,018 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,670 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Failure in writing binary text to file Gigux 7 4,055 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,502 Jul-03-2020, 02:28 PM
Last Post: DeaD_EyE
  Writing to File Issue Flash_Stang 3 2,730 Jun-05-2020, 05:14 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020