PYTHON 50
Code from CSIT 111 on 4/29 regarding reading/writing/appending files Guest on 1st May 2025 04:37:37 PM
  1. import os
  2.  
  3. FILENAME = "myfile.txt"
  4.  
  5.  
  6. # Return a boolean value if the file exists or not
  7. def check_if_file_exists():
  8.         return os.path.exists(FILENAME)
  9.  
  10.  
  11. def read_file():
  12.         f = open(FILENAME, 'r')
  13.         content = f.read()
  14.         f.close()
  15.         print(content)
  16.  
  17. # write empty file
  18. def write_empty_file():
  19.         f = open(FILENAME, 'w')
  20.         f.write("")
  21.         f.close()
  22.  
  23. # append stuff to a file
  24. def append_to_file(stuff):
  25.         f = open(FILENAME, 'a')
  26.         f.write(stuff + "\n")
  27.         f.close()
  28.  
  29.  
  30. def take_attendance():
  31.         done = False
  32.         while not done:
  33.                 current_name = input("Enter a name:\n")
  34.                 if current_name == "done":
  35.                         done = True
  36.                 else:
  37.                         append_to_file(current_name)
  38.  
  39.  
  40. # print(check_if_file_exists())
  41.  
  42. # read the file into an array
  43. # sort the array alphabetically
  44. def sort_attendance():
  45.         lines = []
  46.         f = open(FILENAME, 'r')
  47.         for line in f:
  48.                 lines.append(line)
  49.         lines.sort()
  50.         return lines
  51. #
  52. # if check_if_file_exists():
  53. #       # read_file()
  54. #       # #take_attendance()
  55. #       # lines = sort_attendance()
  56. #       # write_empty_file()
  57. #       # for line in lines:
  58. #       #       append_to_file(line)
  59. #       # # read_file()
  60. #
  61. # else:
  62. #       print("The file isn't found!!!")
  63. # # if check_if_file_exists():
  64.  
  65. happy_song = "Happy%Pharrell Williams"
  66. time_song = "Time%Pink Floyd"
  67. happy = happy_song.split("%")
  68. timey = time_song.split("%")
  69. print(happy[0] + " by " + happy[1])
  70. print(timey[0] + " by " + timey[1])

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.