0% found this document useful (0 votes)
4 views

File Python File Operation (With Examples)

The document provides an overview of file operations in Python, including how to open, read, write, and close files. It explains different modes for opening files, such as read ('r'), write ('w'), and append ('a'), and emphasizes the importance of closing files to free resources. Additionally, it introduces the 'with...open' syntax for better file handling and exception management.

Uploaded by

sammikumari1987
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

File Python File Operation (With Examples)

The document provides an overview of file operations in Python, including how to open, read, write, and close files. It explains different modes for opening files, such as read ('r'), write ('w'), and append ('a'), and emphasizes the importance of closing files to free resources. Additionally, it introduces the 'with...open' syntax for better file handling and exception management.

Uploaded by

sammikumari1987
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
PRO
Courses Tutorials Examples Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
Learn Python Interactively
(https://programiz.pro/learn/master-python?
Skip Ad
utm_source=tutorial-sidebar-
nav&utm_campaign=programiz&utm_medium=referral)

Python Introduction
Python File I/OPython File
Python Flow Control
Operation
A file is a container in computer storage devices used for storing data.
Python Functions

When we want to read from or write to a file, we need to open it first.


Python Datatypes When we are done, it needs to be closed so that the resources that are
tied with the file are freed.
Python Files
Hence, in Python, a file operation takes place in the following order:
Python File (/python-
Operation programming/file-
1. Open a file
operation)
2. Read or write (perform operation)
Python (/python-
Directoryprogramming/directory) 3. Close the file

Python (/python-
Exceptionprogramming/exceptions)

Exception(/python-
Handling programming/exception- Opening Files in Python
handling)

User- (/python-
In Python, we use the open() method to open files.
defined programming/user-
Exception defined-exception) To demonstrate how we open files in Python, let's suppose we have a
file named test.txt with the following content.
Python Object & Class

Python Advanced Topics

Python Date and time

Opening Files in Python


Thank you for printing our contentNow, let's try to open data
at www.domain-name.com. from
Please this back
check file using thenew
soon for function.
contents.
open()

(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now # open file in current directory
banner&utm_campaign=programiz&utm_medium=referral)
file1 = open("test.txt")
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
PRO
Courses Tutorials Examples Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
Here,www.domain-name.com
we have created a file object named file1 . This object can be
used to work with files and directories.
Skip Ad
By default, the files are open in read mode (cannot be modified). The
code above is equivalent to

file1 = open("test.txt", "r")

Here, we have explicitly specified the mode by passing the "r"

argument which means file is opened for reading.

Different Modes to Open a File in Python

Mode Description

r Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist
w
or truncates the file if it exists.

Open a file for exclusive creation. If the file already exists,


x
the operation fails.

Open a file for appending at the end of the file without


a
truncating it. Creates a new file if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)

Python Tutorials

Python open()
(/python-
programming/methods/built-
in/open) Here's few simple examples of how to open a file in different modes,
Working with CSV files in Python
(/python-programming/working- file1 = open("test.txt") # equivalent to 'r' or 'rt'
with-csv-files) file1 = open("test.txt",'w') # write in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode
Python print()
(/python-
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
programming/methods/built-
in/print)
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now Reading Files in Python (https://programiz.pro/learn/master-python?utm_source=sticky-
Python JSON
banner&utm_campaign=programiz&utm_medium=referral)
After we open a file, we
Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
(/python-programming/json)
Try use the read() method to read its contents.
Courses Tutorials Examples Search tutorials & examples
(/) PRO floating&utm_campaign=programiz&utm_medium=referral)
Python CSV For example,
www.domain-name.com
(/python-programming/csv)

Reading CSV files in Python # open a file


Skip Ad
(/python-programming/reading-csv- file1 = open("test.txt", "r")
files)
# read the file
read_content = file1.read()
print(read_content)

Output

This is a test file.


Hello from the test file.

In the above example, we have read the test.txt file that is available
in our current directory. Notice the code,

read_content = file1.read

Here, file1.read() reads the test.txt file and is stored in the


read_content variable.

Closing Files in Python


When we are done with performing operations on the file, we need to
properly close the file.

Closing a file will free up the resources that were tied with the file. It is
done using the close() method in Python. For example,

# open a file
file1 = open("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
This is a test file.
Hello from the test file.
(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
Here, we have used the close() method to close the file.
PRO
Courses Tutorials Examples Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
Afterwww.domain-name.com
we perform file operation, we should always close the file; it's a
good programming practice.
Skip Ad

Exception Handling in Files


If an exception occurs when we are performing some operation with
the file, the code exits without closing the file. A safer way is to use a
try...finally (/python-programming/exception-handling) block.

Let's see an example,

try:
file1 = open("test.txt", "r")
read_content = file1.read()
print(read_content)

finally:
# close the file
file1.close()

Here, we have closed the file in the finally block as finally always
executes, and the file will be closed even if an exception occurs.

Use of with...open Syntax


In Python, we can use the with...open syntax to automatically close
the file. For example,

with open("test.txt", "r") as file1:


read_content = file1.read()
print(read_content)

Note: Since we don't have to worry about closing the file, make
a habit of using the with...open syntax.
Thank you for printing our contentWriting to Files in Please
at www.domain-name.com. Python
check back soon for new contents.

(https://programiz.pro/learn/master-python?utm_source=sticky-
There are two things we need to remember while writing to a file.
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
If we try to open a filetutorials
that doesn't exist, a new file is created.
Courses Tutorials Examples Search & examples
(/) PRO floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
If a file already exists, its content is erased, and new content is
added to the file.
Skip Ad

In order to write into a file in Python, we need to open it in write mode


by passing "w" inside open() as a second argument.

Suppose, we don't have a file named test2.txt. Let's see what


happens if we write contents to the test2.txt file.

with open(test2.txt', 'w') as file2:

# write contents to the test2.txt file


file2.write('Programming is Fun.')
fil2.write('Programiz for beginners')

Here, a new test2.txt file is created and this file will have contents
specified inside the write() method.

Writing to Python Files

Python File Methods


There are various methods available with the file object. Some of them
have been used in the above examples.

Here is the complete list of methods in text mode with a brief


description:

Method Description

Closes an opened file. It has no effect if the file


close()
is already closed.
Thank you for printing our content at www.domain-name.com. Please checkthe
Separates back soon for new
underlying contents.
binary buffer from
detach()
the TextIOBase and returns it.
(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Returns an integer number (file descriptor) of
fileno()
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
Courses Tutorials Examples Search the file.
tutorials & examples
(/) PRO floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
flush() Flushes the write buffer of the file stream.

Skip Ad isatty() Returns True if the file stream is interactive.

Reads at most n characters from the file.


read( n )
Reads till end of file if it is negative or None .

Returns True if the file stream can be read


readable()
from.

Reads and returns one line from the file. Reads


readline( n =-1)
in at most n bytes if specified.

Reads and returns a list of lines from the file.


readlines( n =-1) Reads in at most n bytes/characters if
specified.

seek( offset , Changes the file position to offset bytes, in


from = SEEK_SET ) reference to from (start, current, end).

Returns True if the file stream supports


seekable()
random access.

Returns an integer that represents the current


tell()
position of the file's object.

truncate( size = Resizes the file stream to size bytes. If size


None ) is not specified, resizes to current location.

Returns True if the file stream can be written


writable()
to.

Writes the string s to the file and returns the


write( s )
number of characters written.

writelines( lines ) Writes a list of lines to the file.


Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now Video: Reading and Writing Files in Python
(https://programiz.pro/learn/master-python?utm_source=sticky-
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
Courses Tutorials Examples Search tutorials & examples
(/) PRO floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

Skip Ad
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
PRO
Courses Tutorials Examples Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

Skip Ad

Previous Next
Tutorial: Tutorial:
(/python- (/python-
Python programming/dictionary) Python programming/directory)
Dictionary Directory

Share on:

(https://www.facebook.com/sharer/sharer.php? (https://twitter.com/intent/tweet?
u=https://www.programiz.com/python- text=Check%20this%20amazing%20article%20on%20Python%20File%20I/O
programming/file-operation) programming/file-operation)

Did you find this article helpful?

Related Tutorials

Python Library Python Tutorial Python Library Python Tutorial

Python open() Python print() Python JSON


Working
Thank you for printing our with
content CSV files
at www.domain-name.com. Please check back soon for new contents.
in Python
(/python- (/python- (/python-
(https://programiz.pro/learn/master-python?utm_source=sticky-
36% off programming/methods/built-
Learn to code by doing. Try hands-on Python with Programiz PRO. Claim Discount Now programming/methods/built- programming/json)
banner&utm_campaign=programiz&utm_medium=referral)
in/open) (/python- in/print)
Try Programiz (https://programiz.pro/learn/master-python?utm_source=nav-
Courses programming/working-
Tutorials Examples Search tutorials & examples
(/) PRO floating&utm_campaign=programiz&utm_medium=referral)
with-csv-files)
www.domain-name.com

Skip Ad

You might also like