Creating and Manipulating Files: File Handling
Creating and Manipulating Files: File Handling
SoftUni Team
Technical Trainers
Software University
https://softuni.org
Table of Contents
sli.do
#python-advanced
3
Python File Object
Built-In Functions to Create and Manipulate Files
4
Python File Object
Built-in functions to create and manipulate files
io module is the default module for accessing files
Don't need to import it
open() returns a file object whose type depends on:
The mode
File operations such as reading and writing
Files in a text mode ('w', 'r', 'wt', 'rt', etc.) returns a
TextIOWrapper
5
Opening a File
Opens a File and Returns a File Object
6
open() Function
open() function in Python opens a file and returns a file
object file = open('text.txt', 'r')
The arguments are file name and the mode (reading and
etc.)
All arguments except file are optional and have default
values
If the file is not in the current directory, the full path to the
file can be provided file = open('D:\\text.txt', 'r')
7
open() Function With Invalid File
If the file does not exist, FileNotFoundError is thrown
file = open('invalid.txt', 'r') # FileNotFoundError
8
File Modes
The mode argument is optional and specifies the mode for manipulating the
file
Its default value is 'r' - open for reading in text mode
File modes in Python
w - open for writing, truncating the file first
x - create a new file and open it for writing
a - open for writing, appending to the end of the file if it exists
t - text mode (default)
b - binary mode
+ - open a disk file for updating (reading and writing)
9
Problem: File Opener
Create program that opens the file called 'text.txt'
If the file is found, print 'File found'
If the file is not found, print 'File not found'
try:
text_file = open('text.txt', 'r')
print("File found")
except FileNotFoundError:
print("File not found")
10
Reading a File
Build-In Methods for Reading from File
1
Reading Functions - read()
Returns the first n bytes of the file
Returns the entire file if number of bytes is not passed as an
argument
file = open("asd.txt") # 'Hello, SoftUni!'
print(file.read(2)) # 'He'
print(file.read(2)) # 'll'
print(file.read(2)) # 'o,'
print(file.read()) # ' SoftUni!'
12
Reading Functions - readline()
Returns at most n bytes of a single line of a file
It does not read more than one line
If no argument is passed, the entire line (or rest of the line)
is read
file = open("text.txt") # 'Hello, SoftUni!'
print(file.readline(5)) # 'Hello'
print(file.readline(5)) # ' ,Sof'
print(file.readline(5)) # 'tUni!'
print(file.readline()) # '' Goes to the new line
print(file.readline(5)) # 'Secon' Print second line
13
Reading Functions - readlines()
Read the remaining lines from the file object and returns
them as a list
file = open("text.txt")
print(file.readlines())
# ['Every\n', 'Word\n', 'is\n', 'line']
Keep in mind every line in the file treats the new line
symbol as a string file = open("text.txt")
lines = file.readlines()
[print(line, end="") for line in lines]
14
Looping Over a File Object
To return all lines from a file you can loop over it
More memory efficient and fast manner
Simple and easy to read
16
Writing and Creating a File
Write, Append, Close Methods and with Statement
1
Creating and Writing a File
Using 'w' (write) mode creates a file with the given name
If the file exists, its overwritten
file = open('python.txt', 'w')
# Creates or open the file
18
Append to a File
Using 'a' mode, open a file and write at the end of the file
If the file is not existing, it's created
file = open('python.txt', 'a')
file.write("This is the write command.\n")
file.write("It allows us to write in a particular file")
file.close()
20
with Statement
Files opened with with statement will be closed
automatically once it leaves the with block
Provide much cleaner syntax and exceptions
handling
21
Problem: File Writer
Create a program that creates a file called
'my_first_file.txt'
In that file write a single line with the content: 'I just
created my first file!'
created_file = open('my_first_file.txt', 'w')
created_file.write('I just created my first file!')
22
Deleting a File
OS module, Check File Exists and Delete File
2
Deleting a File (1)
To delete a file, you must import the os module
import os
os.remove("python.txt")
os.remove("D:\\text.txt") # Can use full path
24
Deleting a File (2)
Keep in mind if the file does not exist, an error will
be raised
To avoid getting an error
Check whether the file exists
Delete file import os
file_path = "text.txt"
if os.path.exists(file_path):
os.remove(file_path)
25
Problem: File Delete
Create a program that deletes the file you created in the
previous task
If you try to delete the file multiple times, print the
message: 'File already deleted!'
import os
try:
os.remove('my_first_file.txt')
except FileNotFoundError:
print("File already deleted!")
26
Practice
Live Exercise in Class (Lab)
Summary
©
© SoftUni
SoftUni –– https://softuni.org.
https://softuni.bg. Copyrighted
Copyrighted document.
document. Unauthorized
Unauthorized copy,
copy, reproduction
reproduction or
or use
use isis not
not permitted.
permitted.
Trainings @ Software University (SoftUni)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg, softuni.org
Software University Foundation
softuni.foundation
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg
30
License
31