File Handling - Text Files
File Handling - Text Files
– File handling
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• INPUT
text_file=open(‘sample_file.txt’,‘wt’)
text_file.write(‘This is line one \n’)
text_file.write(‘This is line two \n’)
text_file.close()
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• FILE-HANDLING - WRITING
filename=‘sample_file.txt’
with open(filename,‘wt’) as file:
file.write(‘This is line one \n’)
file.write(‘This is line two \n’)
# don’t need to close the file with #
this method
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
TASK 1
Joe Bloggs
23 Any Street
AG1 4NM
• …called address_book
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
TASK 2
car_db=open(‘car_database.txt’,‘a’)
car_reg=str(input(‘Type in car registration’))
car_db.write(car_reg)
car_db.close()
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• As well as writing to and reading from files, you
can append (‘add’) to existing files (METHOD 2)
filename=‘car_database.txt’
car_registration=str(input(‘Type in car number plate’))
with open(filename,‘a’) as file:
file.write(car_registration)
# again… no need to CLOSE the file if you use WITH OPEN
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• TASK 4
text_file=open(‘sample_file.txt’,‘rt’)
print(text_file.read())
text_file.close()
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• FILE-HANDLING - READING
filename=‘sample_file.txt’
with open(filename) as file:
whole_file=file.readlines()
import os
os.startfile(‘sample_file.txt’)
4.2 Fundamentals of data structures
4.2.1.3 file handling - text
• TASK 6