27. Reading Files - tomaslt99/Python-language-tutorials GitHub Wiki
Reading Files:
* r – reads
* r+ – read and writes (add “+” sign)
* w – writes
* a – append
syntax:
employee_file = open(“employees.txt”, “r”)
File – employees.txt
Jim – Salesman
pam – Receptionist
Oscar – Accountant
Check if the file is readable.
employee_file = open(“employees.txt”,”r”)
print(employee_file.readable())
employee_file.close()
Displays the whole file.
employee_file = open(“employees.txt”,”r”)
print(employee_file.read())
employee_file.close()
Display individual lines
employee_file = open(“employees.txt”,”r”)
print(employee_file.readline()) # Displays 1st line
print(employee_file.readline()) # Displays 2nd line
employee_file.close()
Display file in a list.
employee_file = open(“employees.txt”,”r”)
print(employee_file.readlines())
employee_file.close()
Specifying to display specific lines in a file.
employee_file = open(“employees.txt”,”r”)
print(employee_file.readlines()[2])
employee_file.close()