0% found this document useful (0 votes)
32 views27 pages

5.1 - Text Files

Materi about text files
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views27 pages

5.1 - Text Files

Materi about text files
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Topic 5.

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.

Copyright 2020 MANYPIXELS PTE LTD

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

How to create file object

How to read file in Python

How to write a file using Python


Files Overview

A file is a collection of data that is stored on secondary


storage like a disk or a thumb drive (or USB flashdisk)

Accessing a file means establishing a connection between


the file and the program and moving data between the two

File header describes the metadata of the file (name, size, type, etc.)

The contents of the file

End of file (EOF), a special character denoting the end of a file

https://realpython.com/read-write-files-python/
Types of Files

There are two general types of files that can be handled by Python:

1. Text files 2. Binary files


A text file is organized as Unicode/ASCII All the information is taken directly
data and is generally human readable. without translation as a sequence
of bytes. Not human readable.
File Objects or Stream

When opening a file, you create a


file object or file stream that is a
connection between the file
information on disk and the
program.

The stream contains a buffer of the


information from the file, and
provides the information to the
program.
The Process
Buffering

➔ Reading from a disk is very


slow. Thus the computer will
read a lot of data from a file in
the hopes that, if you need the
data in the future, it will be
buffered in the file object.

➔ This means that the file object


contains
a copy of information from the
file called a cache (pronounced
"cash")
Making a File Object

my_file = open("your_file.txt", "r")

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

When opened, the name of the file can come in one of


two forms:

➔ "file.txt" assumes the file name is file.txt


and it is located in the current program
directory

➔ "c:\\bill\\file.txt" is the fully qualified


file name and includes the directory
information

A common error:

➔ FileNotFoundError: Maybe we declared wrong


file name or did not include the right directory
information
Code Example: Read a File

Example 1

my_file = open("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:
print(line, end = '')

# flush the buffer ^^


my_file.close()

Example 2 (The Fully Qualified Version)

my_file_fully_qualified = open("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 = '')

# flush the buffer ^^


my_file_fully_qualified.close()
Fully Qualified File Path: A Common Error (in Python 3)

This will be interpreted as escape characters


A common error

my_file_fully_qualified = open("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 = '')

# flush the buffer ^^


my_file_fully_qualified.close()

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 = '')

# flush the buffer ^^


my_file_fully_qualified.close()
File Modes

https://docs.python.org/3/library/functions.html#open
Careful with write modes

➔ Be careful if you open a file with the 'w'


mode. It sets an existing file’s contents
to be empty, destroying any existing data.

➔ The 'a' mode is nicer, allowing you to


write on the end of an existing file without
changing the existing contents
Triggering Question 1

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

a. my_file = open("test.txt", "wt") d. my_file = open("test.txt", "w")

b. my_file = open("test.txt", "r") e. my_file = open("test.txt", "rt")

c. my_file = open("/documents/codes/test.txt", "rb")

15
Text files use strings

If you are interacting with text files, remember


that everything is a string, everything read is a
string. if you write to a file, you can only write a
string
Getting File Contents
Once you have a file object:

➔ 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)

my_file = open("my_file.txt", "r") my_file = open("my_file.txt", "r")

# Print entire lines # Print line 1


print(my_file.read()) print(my_file.readline(), end = '')
# Print line 2
# flush the buffer ^^ print(my_file.readline(), end = '')
my_file.close() # Print line 3
print(my_file.readline(), end = '')

# flush the buffer ^^


my_file.close()
More File Reads

➔ fileObject.readlines() ➔ for line in fileObject:


iterator to go through the lines of a file
returns a single list of all the lines from
the file

my_file = open("nama_hari.txt", "r") my_file = open("nama_hari.txt", "r")

# Print entire lines # Print entire lines


print(my_file.readlines()) for line in my_file:
print(line, end = '')
# flush the buffer ^^
my_file.close() # flush the buffer ^^
my_file.close()
More File Reads: Non Latin Alphabet Characters

➔ Sometimes, it is necessary to use encoding = UTF-8 in open() function


A common error:
my_file = open("jujutsu_kaisen_op1.txt", "r")

# Print entire lines


print(my_file.read())

# flush the buffer ^^


my_file.close()

Solution:

my_file = open("jujutsu_kaisen_op1.txt", "r",encoding = "UTF-8")


Triggering Question 2

What does this program do? If test.txt existed, what


Assume that no file named would have happened if
‘test.txt’ existed in the the program was
program directory executed?

my_file = open("test.txt", "rt") my_file = open("test.txt", "r")

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

you add file = file_to_write to the print() command


Code Example: Write a File

my_file = open("my_file_w_mode.txt", "w")

print("Mantappu Jiwaa!", file = my_file)


print("", file = my_file)
print(12345678, file = my_file)

my_file.close()
Close Method

When the program is finished with a file, we close the file

1. flush the buffer contents from the computer to the file


2. tear down the connection to the file

close is a method of a file obj file_obj.close()

All files should be closed!


Code Example: Using Close Method

input_file = open("my_file.txt","r")
output_file = open("my_file_inverse.txt","w")
line_counter = 1

for line_str in input_file:


new_str = ''
line_str = line_str.strip() # get rid of carriage return (newline)

for char in line_str:


new_str = char + new_str

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)

my_file_example = open('Tes.txt', 'w+')


print('ABCD', file = my_file_example)
print('EFGH')
print(1234, file = my_file_example)
my_file_example.close()

1. Assuming Tes.txt is not yet existed, what is written in Tes.txt after the program
execution?
Review Question (2)

my_file_example = open('Tes.txt', 'w+')


print('ABCD',file = my_file_example)
print('EFGH')
print(1234, file = my_file_example)
my_file_example.close()

2. What happen if this program is executed twice?


Q&A Session

You might also like