Reading Files
Mode
r - Opens a file for reading. (default)
w - Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x - Opens a file for exclusive creation. If the file already exists, the operation fails.
a - Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
t - Opens in text mode. (default)
b - Opens in binary mode.
+ - Opens a file for updating. (reading and writing)
employees.txt
Jim - Salesman Dwight - Salesman Pam - Receptionist Michael - Manager Oscar - Accountant Toby - Human Resources Kelly - Customer Service
employee_file = open("../employees.txt", "r") if employee_file.readable(): print(employee_file.read()) else: print("Access denied.") employee_file.close() //Output : Jim - Salesman // Dwight - Salesman // Pam - Receptionist // Michael - Manager // Oscar - Accountant // Toby - Human Resources // Kelly - Customer Service
employee_file = open("../employees.txt", "r") if employee_file.readable(): print(employee_file.readline()) else: print("Access denied.") employee_file.close() //Output : Jim - Salesman
employee_file = open("../employees.txt", "r") if employee_file.readable(): print(employee_file.readlines()[1]) else: print("Access denied.") employee_file.close() //Output : Dwight - Salesman
employee_file = open("../employees.txt", "r") if employee_file.readable(): for employee in employee_file.readlines(): print(employee) else: print("Access denied.") employee_file.close() //Output : Jim - Salesman // // Dwight - Salesman // // Pam - Receptionist // // Michael - Manager // // Oscar - Accountant // // Toby - Human Resources // // Kelly - Customer Service