Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Chapter 8

File Handling
Topics
• How to open & close a text file
• How to read a text file
• How to write into a text file
How to open & close a text file
• Syntax to open file:

x = open(“path to file”, “mode”)

• x is a file handler. It can be any names


• mode: r, r+, w, w+, a, a+
• Syntax to close file

x.close()
File Open Mode
How to read a text file
• A mode can be used: r, r+, w+, a+
• Functions to read:
• read() -> read all data inside the text file at once
• read(1) -> read a single data inside the text file
• readlines() -> read data inside the text file, line by line
How to read a text file
How to read a text file
How to write data into a text file
• The open file mode can be used: r+, w, w+, a, a+
• Syntax:
• x.write(data)
• x is a file handler
How to write data into a text file

• What’s the difference between using append mode (a) and write mode
(w), right after writing a data into the file?
• What does \n mean?
Problem to discuss
• Suppose, initially we have a text file mydata.txt with some datas
inside:

• Let say, then I write a code to add a text line into the file
• Finally, I will try to print all the data file

• The code is in the next slide…


Problem to discuss

The problem is: why the script can not print all datas inside the file??
Then… try to find the solution to solve that problem
Challenge
• Write a Python script to read a README text file. The output is a statistic
that contains total number of all character, number of consonant, number
of vowel, and number of character which not a letter
• Write a Python script to read input data profile of students: Student ID,
name, place of birth, date of birth, and address. Each time an input is
given, then add the data input to a text file, with format:
StudentID#Name#Place of Birth#Date of Birth#Address
Example of contents of the text file data, after several data inputs have
been given:
K3512201#Rosihan Ari#Boyolali#01-09-1979#Jl. Apel No 4 Solo
K3512202#Dwi Amalia#Kudus#17-09-1979#Jl. Durian No 8 Solo

You might also like