# this is main code
file = open(
file='demo.txt',
='r'
mode
)= file.read()
content print(content)
Hello World!
I love Python
Juma Shafara
November 1, 2023
Python File Handling, creating files in python, deleting files in python, modifying files in python, reading files in python
Python allows us to read, write, create and delete files. This process is called file handling. This is what we will discuss in this lesson
Before we continue, we have a humble request, to be among the first to hear about future updates of the course materials, simply enter your email below, follow us on (formally Twitter), or subscribe to our YouTube channel.
open()
functionThe open()
function allows us to read, create and update files
It takes 2 parameters:
file
- the file or file path to be openedmode
- the mode in which a file is opened forThe mode is a string that can either be any of the following:
Mode | Meaning |
---|---|
'r' |
Open a file for reading |
'w' |
Open a file for writing, creates the file if it does not exist |
'a' |
Open a file for writing, appends to the end of the file |
'x' |
Open a file for creating, fails if file already exists |
To better explain this, let us say we have a folder named my_folder
.
Inside my_folder
we have the following files:
demo.txt
main_code.py
The content of the demo.txt
file is the following
Hello World!
I love Python
Now our goal is to read the content of the demo.txt
file and then print it using the main_code.py
file
To achieve this, we will use the open()
function with 'r'
mode.
Hello World!
I love Python
We can also read each line using the readline()
method.
In simplest terms, writing a file means modifying the content of a file or creating it if it doesnot exist yet.
In Python, there are 2 modes to write to file.
'w'
- overwrites content of a file, creates file if it does not exist'a'
- appends content to the end of a file, creates the file if it does not existExample To better explain this, lets say we have a folder named my_folder
. Inside my_folder
we have the following files
demo.txt
main_code.py
The content of the demo.txt
file is the following
I love Python
In this example, we will use the 'w'
mode which will overwrite(replace) the content of the file
When the above code is run, the content of the file demo.txt
will be this:
I love JavaScript
Another example, this time we will use the a
mode which will append or add content to the end of the file
When the above script is run, the content of the demo.txt
file will be this:
I love Python and JavaScript
To delete a file, use the os
module. The os
modules contains the remove()
method which we can use to delete files.