PYTHON
50
Code from CSIT 111 on 4/29 regarding reading/writing/appending files Guest on 1st May 2025 04:37:37 PM
- import os
- FILENAME = "myfile.txt"
- # Return a boolean value if the file exists or not
- def check_if_file_exists():
- return os.path.exists(FILENAME)
- def read_file():
- f = open(FILENAME, 'r')
- content = f.read()
- f.close()
- print(content)
- # write empty file
- def write_empty_file():
- f = open(FILENAME, 'w')
- f.write("")
- f.close()
- # append stuff to a file
- def append_to_file(stuff):
- f = open(FILENAME, 'a')
- f.write(stuff + "\n")
- f.close()
- def take_attendance():
- done = False
- while not done:
- current_name = input("Enter a name:\n")
- if current_name == "done":
- done = True
- else:
- append_to_file(current_name)
- # print(check_if_file_exists())
- # read the file into an array
- # sort the array alphabetically
- def sort_attendance():
- lines = []
- f = open(FILENAME, 'r')
- for line in f:
- lines.append(line)
- lines.sort()
- return lines
- #
- # if check_if_file_exists():
- # # read_file()
- # # #take_attendance()
- # # lines = sort_attendance()
- # # write_empty_file()
- # # for line in lines:
- # # append_to_file(line)
- # # # read_file()
- #
- # else:
- # print("The file isn't found!!!")
- # # if check_if_file_exists():
- happy_song = "Happy%Pharrell Williams"
- time_song = "Time%Pink Floyd"
- happy = happy_song.split("%")
- timey = time_song.split("%")
- print(happy[0] + " by " + happy[1])
- print(timey[0] + " by " + timey[1])