Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Student Exercise. Create, Access and Update a counter on a text file
- from os.path import getsize
- arch = "contador.txt"
- def archExist(name):
- try:
- fin = open(name) # 'rt' is the default mode
- fin.close()
- return True # just do the return here, no need for 'else: return True' later
- except FileNotFoundError:
- return False
- # Create a text file containing a count of the given value
- def crearArch(name, count): # 'count' is the value to be written to the file
- # I don't see any point in using a "Try:" here.
- # Anything that went wrong would be well beyond your control. Such as "disk full" !!
- fout = open(name, 'w')
- fout.write(str(count))
- fout.close()
- if count == 1:
- print(f"File {name} created OK")
- else:
- print(f"File {name} updated OK. New count is {count}")
- def archVacio(none):
- return getsize(none) == 0 # shorthand method. Returns True or False based on the test
- if not archExist(arch) or archVacio(arch):
- crearArch(arch, 1) # create initial 'arch' file with a count of one
- else:
- # Again, I see no point in using "Try" here. You have already proved the file exists
- afile = open(arch)
- newctr = int(afile.read()) + 1
- afile.close()
- crearArch(arch, newctr) # re-create arch file with the latest count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement