Advertisement
acclivity

pyMaintainCounterOnTextFile

May 25th, 2022
626
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Student Exercise. Create, Access and Update a counter on a text file
  2.  
  3. from os.path import getsize
  4.  
  5. arch = "contador.txt"
  6.  
  7. def archExist(name):
  8.     try:
  9.         fin = open(name)            # 'rt' is the default mode
  10.         fin.close()
  11.         return True                 # just do the return here, no need for 'else: return True' later
  12.     except FileNotFoundError:
  13.         return False
  14.  
  15.  
  16. # Create a text file containing a count of the given value
  17. def crearArch(name, count):         # 'count' is the value to be written to the file
  18.     # I don't see any point in using a "Try:" here.
  19.     # Anything that went wrong would be well beyond your control. Such as "disk full" !!
  20.     fout = open(name, 'w')
  21.     fout.write(str(count))
  22.     fout.close()
  23.     if count == 1:
  24.         print(f"File {name} created OK")
  25.     else:
  26.         print(f"File {name} updated OK. New count is {count}")
  27.  
  28. def archVacio(none):
  29.  
  30.     return getsize(none) == 0           # shorthand method. Returns True or False based on the test
  31.  
  32.  
  33. if not archExist(arch) or archVacio(arch):
  34.     crearArch(arch, 1)          # create initial 'arch' file with a count of one
  35. else:
  36.     # Again, I see no point in using "Try" here. You have already proved the file exists
  37.     afile = open(arch)
  38.     newctr = int(afile.read()) + 1
  39.     afile.close()
  40.     crearArch(arch, newctr)      # re-create arch file with the latest count
Advertisement
RAW Paste Data Copied
Advertisement