5.1 - Text Files
5.1 - Text Files
1:
Text Files
CSGE601020 - Dasar-Dasar
Pemrograman 1
Acknowledgement
This slide is an adapted version of Text Files slides used in DDP1 Course
(2020/2021) by Hafizh Rafizal Adnan, M.Kom, and Files and Exceptions I
slides by Punch and Enbody (2013)
Some of the design assets used in these slides were provided by ManyPixels
under an nonexclusive, worldwide copyright license to download, copy, modify,
distribute, perform, and use the assets provided from ManyPixels for free,
including for commercial purposes, without permission from or attributing the
creator or ManyPixels.
Some additional contents, illustrations and visual design elements are provided by
Lintang Matahari Hasani, M.Kom. (lintang.matahari01[at]cs.ui.ac.id)
In this session, you will learn ...
What a file is
File header describes the metadata of the file (name, size, type, etc.)
https://realpython.com/read-write-files-python/
Types of Files
There are two general types of files that can be handled by Python:
my_file is the file object. It contains the buffer of information. The open
function creates the connection between the disk file and the file object.
The first quoted string is the file name on disk, the second is the mode to open
it (here,"r" means to read)
Mind the File Path
A common error:
Example 1
# print each line from the file by preserving the new lines from the file
for line in my_file:
print(line, end = '')
# print each line from the file by preserving the new lines from the file
for line in my_file_fully_qualified:
print(line, end = '')
# print each line from the file by preserving the new lines from the file
for line in my_file_fully_qualified:
print(line, end = '')
Solutions: Use raw string (put r before the string), double backslashes, or single slashes (/)
my_file_fully_qualified = open(r"C:\Users\Imairi\Documents\Ajar\my_file.txt", "r")
print("Reading from my_file.txt:")
# print each line from the file by preserving the new lines from the file
for line in my_file_fully_qualified:
print(line, end = '')
https://docs.python.org/3/library/functions.html#open
Careful with write modes
Assume we want to open a file ‘test.txt’ located in the Which of the following is the correct way to open
same directory with the open_file.py program as the file for reading as a text file in open_file.py?
illustrated below. Select all that apply.
/
│
├── documents/
| ├── codes/ ← Your current working directory is here
| │ └── test.txt ← Accessing this file
| │ └── open_file.py
| └── nilai_ddp1.txt
15
Text files use strings
➔ fileObject.read() ➔ fileObject.readline()
reads the entire contents of the file as a string and delivers the next line as a string
returns it. It can take an optional argument integer to
limit the read to N bytes, that is
fileObject.read(N)
Solution:
number = 0 number = 0
for line in my_file: for line in my_file:
number += 1 number = number + len(line)
print(number) print(number)
my_file.close()
1 my_file.close()
2
20
Writing to a File
➔ Once you have created a file object, opened for writing, you can use the print() command
my_file.close()
Close Method
input_file = open("my_file.txt","r")
output_file = open("my_file_inverse.txt","w")
line_counter = 1
print(new_str,file = output_file)
# observe progress
print('Line {:d}: {:s} reversed is {:s}'.format(line_counter,line_str,new_str))
line_counter += 1
input_file.close()
output_file.close()
Review Question (1)
1. Assuming Tes.txt is not yet existed, what is written in Tes.txt after the program
execution?
Review Question (2)