0% found this document useful (0 votes)
4 views7 pages

Python File

The document provides an overview of file handling in Python, explaining the importance of files for data storage and the basic operations such as opening, reading, writing, and closing files. It details various modes for opening files, error handling, and best practices like using the 'with' statement for automatic resource management. Additionally, it covers methods for reading and writing data, including the use of 'read()', 'write()', 'seek()', and 'tell()' functions.

Uploaded by

Nirav Desai
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)
4 views7 pages

Python File

The document provides an overview of file handling in Python, explaining the importance of files for data storage and the basic operations such as opening, reading, writing, and closing files. It details various modes for opening files, error handling, and best practices like using the 'with' statement for automatic resource management. Additionally, it covers methods for reading and writing data, including the use of 'read()', 'write()', 'seek()', and 'tell()' functions.

Uploaded by

Nirav Desai
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

Python File

Gaurav Kr. suman MIT10


A file is a location on disk that stores related information and has a name. A
hard-disk is non-volatile, and we use files to organize our data in different
directories on a hard-disk. The RAM (Random Access Memory) is volatile;
it holds data only as long as it is up. So, we use files to store data
permanently. To read from or write to a file, we must first open it. And then
when we’re done with it, we should close it to free up the resources it holds
(Open, Read/Write, Close).

To start Python file i/o, we deal with files and have a few in-built
functions and methods in Python. To open a file in Python, we use the
read() method.
But first, let’s get to the desktop, and choose a file to work with.

1. >>> import os
2. >>> [Link]()
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’

1. >>> [Link]('C:\\Users\\lifei\\Desktop')
2. >>> [Link]()

[‘Adobe Photoshop [Link]’, ‘[Link]’, ‘Backup iPhone7+ 20-1-18’, ‘Burn


[Link]’, ‘ch’, ‘[Link]’, ‘[Link]’, ‘Documents’, ‘Eclipse Cpp
[Link]’, ‘Eclipse Java [Link]’, ‘Eclipse Jee [Link]’, ‘[Link]’,
‘Items for [Link]’, ‘Major temp’, structure’, ‘office [Link]’, ‘Papers’,
‘Remember to [Link]’, ‘To [Link]’, ‘[Link]’]
If this seems new to you, be sure to check out Python Directory.
Now, let’s open Python file ‘To [Link]’.

1. >>> open('To [Link]')

<_io.TextIOWrapper name=’To [Link]’ mode=’r’ encoding=’cp1252′>

But to work with this, we must store it into a Python variable. Let’s do this.

1. >>> todo=open('To [Link]')


2. >>> todo

<_io.TextIOWrapper name=’To [Link]’ mode=’r’ encoding=’cp1252′>

1|Page
We wouldn’t have to change directory if we just passed the full path
of Python file to open(). But let’s work with this for now.

While opening Python file, we can declare our intentions by choosing a


mode. We have the following modes:
Mode Description

r To read a file (default)

w To write a file; Creates a new file if it doesn’t


exist, truncates if it does

x Exclusive creation; fails if a file already exists

a To append at the end of the file; create if doesn’t


exist
t Text mode (default)

b Binary mode

+ To open a file for updating (reading or writing)

Let’s take a couple of examples.

1. >>> todo=open('To [Link]','r+b') #To read and write in binary mode


2. >>> todo=open('To [Link]','a')

Also, it is good practice to specify what encoding we want, because different


systems use a different encoding. While Windows uses ‘cp1252’, Linux uses
‘utf-8’.

1. >>> todo=open('To [Link]',mode='r',encoding='utf-8')

Finally, if you try opening Python file that doesn’t exist, the interpreter will
throw a FileNotFoundError.

1. >>> todo=open('[Link]')

2|Page
Traceback (most recent call last):

File “<pyshell#27>”, line 1, in <module>

todo=open(‘[Link]’)

FileNotFoundError: [Errno 2] No such file or directory: ‘[Link]’

Tell us how do you like the Python Open file Explanation.

When we tried to manually go rewrite the Python file, it threw this error
dialog when we attempted to save it.
So, remember, always close what you open:

1. >>> [Link]()

But if an exception occurs in the middle of our code, the file remains open,
and the resources aren’t freed. To take care of these situations, we put the
close() method in the finally-block.
1. >>> try:
2. f=open('To [Link]')
3. print("Before")
4. print(1/0)
5. finally:
6. [Link]()
Before

Traceback (most recent call last):

File “<pyshell#51>”, line 4, in <module>

print(1/0)

ZeroDivisionError: division by zero

Follow this link, to handle an exception in Python

If you think having to put close() every time you’re done with a Python file
is bunk, use the ‘with’ statement.

3|Page
1. >>> with open('To [Link]') as f:
2. [Link]()
‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for
exam’
With this, it will close the file implicitly as soon as it finishes executing the
statements under the block.

To read the contents of a Python file, we can do one of these:

a. The read() Method


We can use the read() method to read what’s in a Python file.

1. >>> with open('To [Link]') as todo:


2. [Link]()
‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for
examLearn to cook\nLearn to cook’
When we provide an integer argument to read(), it reads that many
characters from the beginning of the Python file.

1. >>> todo=open('To [Link]')


2. >>> [Link](5)
‘Get g’
Now when we call read() without any arguments, it reads the rest of the
Python file.

1. >>> [Link]()
‘roceries\nOrganize room\nPrint labels\nWrite article\nStudy for
examLearn to cook\nLearn to cook’

Notice that it prints a ‘\n’ for a newline. And when we yet read it, it prints
an empty string, because the cursor has reached the end of the Python file.

1. >>> [Link]()
2. ''
3. >>> [Link]()

b. Seek() and tell()


Okay, jokes apart, these two methods let us reposition the cursor and find
its position. tell() tells us where the cursor is.

4|Page
1. >>> todo=open('To [Link]')
2. >>> [Link](5)
‘Get g’

1. >>> [Link]()
5
seek() takes an integer argument, and positions the cursor after that many
characters in the Python file. Along with that, it returns this new position of
the cursor.

1. >>> [Link](0)
1. >>> [Link]()
‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for
examLearn to cook\nLearn to cook’
seek() and tell() are like seekg(), seekp(), tellg(), and tellp() in C++.

To write a Python file, we use the write() method.

1. >>> todo=open('To [Link]')


2. >>> [Link]("HI")
Traceback (most recent call last):

File “<pyshell#56>”, line 1, in <module>

[Link](“HI”)

[Link]: not writable

Here, we did not open the Python file in a writable format. Let’s open it
properly.

1. >>> todo=open('To [Link]','a')


2. >>> [Link]('\nLearn to cook')
14

1. >>> [Link]()
When we checked in the file (refreshed it), we found:
Get groceries
Organize room
Print labels
Write article
Study for exam

5|Page
Learn to cook
Concluding, you can use ‘w’, ‘a’, or ‘x’. The ‘w’ erases the content and writes
over it. So, be careful with it. Also, write() returned 14 here because it
appended 14 characters to Python file.
But you can’t read a Python file if you open it in ‘a’ mode.

1. >>> todo=open('To [Link]','a')


2. >>> [Link]()
Traceback (most recent call last):

File “<pyshell#13>”, line 1, in <module>

[Link]()

[Link]: not readable

To get around this, you’d have to use ‘a+r’.

So, this was all about Python File I/O Tutorial. Hope you like our
explanation.

6|Page

You might also like