unit 4_python
unit 4_python
LEARN
Home > Python Guide > Tutorials > Python Files > Python File I/O
EXAMS
Python Files
Python
ASK File I/O
As a data scientist, you deal with a large amount of data on a regular basis.
CONCEPTS
And this data could come from a variety of sources, including databases,
Excel spreadsheets, flat files, and public websites such as Kaggle. Not just
sources, but any file type such as .csv, .txt, .parquet, and so on. Before you
can begin making sense of the data, you must first understand the basic
Python file operations such as how to access, read, and write data into flat
files so that you can do analytics on them.
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 1/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
Table of content
1 Python File
2 Opening Files in Python
2.1 Mode
2.2 Description
3 Closing Files in Python
4 Writing to Files in Python
4.1 Python write() –
4.2 Python writelines() –
5 Reading Files in Python
5.1 Python read() –
5.2 Python readline() –
5.3 Python readlines() –
6 Python File Methods
7 Frequently Asked Questions
7.1 Q1. How do you write to a file in Python?
7.2 Q2. How do you open and write to a file in Python?
Python File
Files are identified locations on the disc where associated data is stored.
They are used to retain data in non-volatile memory indefinitely (e.g. hard
disk). Because Random Access Memory (RAM) is volatile (it loses data
when the computer is shut off), we employ files to store data for future use
by permanently storing it.
When we wish to read or write to a file, we must first open it. When we’re
finished, it needs to be closed so that the resources associated with the file
may be released. As a result, Python file operations occur in the following
order:
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 2/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
Opening a file
In Python, there are two sorts of files that can be handled: text files and
binary files (written in binary language- 0s and 1s)
Text files – A text file, on the other hand, does not require any special
encoding and may be opened with any ordinary text editor. Each line
of text in this sort of file is terminated with a special character known
as EOL (End of Line), which is the new line character (‘\n’) in Python
by default.
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 3/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
where,
filename – name of the file that the file object has to open
access_mode – attribute of the file that tells which mode a file was
opened in. Default is reading in text mode
For example,
COPY CODE
In this case, the filename is the name of the file with which you want to
communicate, including the file extension. That is, if you have a text file
named myFile.txt, the filename is not simply “myFile.” It’s called
“myFile.txt“. If you’re using Windows, you can also specify the file’s actual
location, such as “C:\MyFolder\myFile.txt“.
Note – The file must be in the same directory as the Python program file;
otherwise, the full location of the file must be written in place of the
filename.
When we open a file, we can define the access mode. Python understands
what you want to do with the file based on the mode parameter in the open
function. We specify whether we wish to read r, write w, or add a to the file
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 4/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
in mode. We can also choose whether to open the file in text or binary mode.
Reading in text mode is the default setting. When reading from a file in this
mode, we get strings. Binary mode, on the other hand, returns bytes and is
the mode to employ when dealing with non-text files such as images or
executable files.
Mode Description
This command opens a file for writing. If the file does not exist, it is
w
created; otherwise, it is truncated.
Opens a file for the purpose of exclusive creation. The operation fails if
x
the file already exists.
Opens a file for adding at the end without truncating it. If the file does
a
not exist, it is created.
‘x’ – Exclusive Creation Mode – This mode is used to generate a file only.
The function call will fail if a file with the same name already exists.
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 5/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
COPY CODE
Syntax:
File_object.close()
Example
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 6/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
COPY CODE
COPY CODE
try:
f = open('myFile.txt', encoding = 'utf-8')
# perform file operations
finally:
f.close()
This ensures that the file is correctly closed even if an exception is generated,
causing the program flow to halt.
When you close a file, you no longer have access to it until you reopen it at a
later time. Any attempt to read or write to a closed file object will result in a
ValueError exception:
COPY CODE
>>> f.read()
Output
The with statement is the most effective technique to close a file. After the
nested code block is finished, this keyword automatically closes the file.
COPY CODE
If you do not use the with keyword or the fileobject.close() function, Python
will close and destroy the file object automatically using the built-in garbage
collector. As a result, it is advisable to utilize the with keyword to control
when the file will be closed.
the end of a file. Keep in mind that when you create a new file object,
Python will create the file if it does not already exist. When making your
first file, you should utilize either the a+ or w+ modes. We must exercise
caution when using the w mode, as it will overwrite the file if it already
exists. As a result, all previous data is deleted.
1. Python write() –
Inserts the string str1 into the text file on a single line.
File_object.write(str1)
2. Python writelines() –
Each string is inserted into the text file for a list of string
elements. Used to insert many strings at once.
Example
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 9/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
COPY CODE
Output
5 eggs
2 tsp baking powder
60g butter
2 cup sugar
If this code is executed, the program will create a new file named recipe.txt
in the current directory if one does not already exist. It gets rewritten if it
exists. Now if we want to add more ingredients to the file, we open the file in
append mode.
COPY CODE
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 10/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
Output
5 eggs
2 tsp baking powder
60g butter
2 cup sugar
2 cup water
250ml skimmed milk
1. Python read() –
File_object.read([n])
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 11/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
Let us use the above Recipe.txt file to carry out the reading Python file
operation.
Example
COPY CODE
>>> f.read() # reads the rest of the data till the end of fil
' butter\n2 cup sugar\n2 cup water\n250ml skimmed milk\n'
2. Python readline() –
File_object.readline([n])
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 12/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
Example
COPY CODE
>>> f.readline()
'2 tsp baking powder\n'
>>> f.readline()
'60g butter\n'
>>> f.readline()
'2 cup sugar\n'
3. Python readlines() –
File_object.readlines()
Example
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 13/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
COPY CODE
Method Description
This function closes an open file. If the file is already closed, it has
close()
no effect.
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 14/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
readable() If the file stream can be read from, this method returns True.
Reads one line from the file and returns it. If n is supplied, it reads
readline(n=-1)
in at most n bytes.
writable() If the file stream can be written to, this method returns True.
Files are useless if you can’t write data to them. To accomplish this, we can
employ the Python write() function. This adds the characters you specify to
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 15/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
the end of a file. Keep in mind that when you create a new file object,
Python will create the file if it does not already exist. When making your
first file, you should utilize either the a+ or w+ modes. We must exercise
caution when using the w mode, as it will overwrite the file if it already
exists. As a result, all previous data is deleted.
1. Python write() – Inserts the string str1 into the text file on a single
line.
COPY CODE
File_object.write(str1)
2. Python writelines() – Each string is inserted into the text file for a
list of string elements. Used to insert many strings at once.
COPY CODE
The open() method in Python allows you to write to a file. To write to a file,
you must supply either “w” or “a” as an argument. “w” overwrites a file’s
existing content, whereas “a” appends material to a file.
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 16/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
For example
COPY CODE
We’ve used the w mode to open our Recipe.txt file. This means we can
make changes to the file we’re working on. You can write to a file in this
mode. It deletes the contents of a file and replaces it with a new one.
Python Files
5 th 6 th 7 th 8 th
9 th 10 th 11 th 12 th
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 17/19
12/21/23, 2:44 PM Python File I/O: Read and Write Files in Python | Python File Operations |
GET STARTED
GET STARTED
BROWSE
Python Files
heap.identify('unique_identifier');
https://www.toppr.com/guides/python-guide/tutorials/python-files/python-file-i-o/ 19/19