0% found this document useful (0 votes)
27 views10 pages

Python File Handling Basics Guide

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)
27 views10 pages

Python File Handling Basics Guide

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

UNIT – V

Python File Handling: Types of files in Python - Opening and Closing files
Reading and Writing files: write() and writelines() methods- append() method
– read() and readlines() methods – with keyword – Splitting words – File
methods - File Positions- Renaming and deleting files.

Python File Handling:

▪ A file is a sequence of bytes on the disk/permanent storage where a group


of related data is stored.
▪ File is created for permanent storage of data.
▪ In programming, Sometimes, it is not enough to only display the data on the
console. Those data are to be retrieved later on, then the concept of file
handling comes. It is impossible to recover the programmatically generated
data again and again.
▪ However, if we need to do so, we may store it onto the file system which is
not volatile and can be accessed every time. Here, comes the need of file
handling in Python. File handling in Python enables us to create, update,
read, and delete the files stored on the file system through our python
program.

The following operations can be performed on a file. In Python, File Handling


consists of following three steps:

 Open the file.

 Process file i.e perform read or write operation.

 Close the file.

Types of File

There are two types of files:

1. Text Files- A file whose contents can be viewed using a text editor is called a text
file. A text file is simply a sequence of ASCII or Unicode characters. Python
programs, contents written in text editors are some of the example of text files.e.g.
.txt,.rtf,.csv etc.
2. Binary Files-A binary file stores the data in the same way as as stored in the
memory. The .exe files,mp3 file, image files, word documents are some of the
examples of binary [Link] can’t read a binary file using a text editor.e.g. .bmp,.cdr
etc.
Text File Binary File

Its Bits represent character. Its Bits represent a custom data.

Less prone to get corrupt as change Can easily get corrupted, corrupt on
reflects as soon as made and can be even single bit change
undone.
Store only plain text in a file. Can store different types of data
(audio, text,image) in a single file.

Widely used file format and can be Developed for an application and can
opened in any text editor. be opened in that application only.

Mostly .txt,.rtf are used as extensions Can have any application defined
to text files. extension.

Opening and Closing Files

▪ To perform file operation, it must be opened first then after reading, writing,
editing operation can be performed.
▪ To create any new file then too it must be opened. On opening of any file ,a file
relevant structure is created in memory as well as memory space is created to
store contents.
▪ Once we are done working with the file, we should close the file. Closing a file
releases valuable system resources. In case we forgot to close the file, Python
automatically close the file when program ends or file object is no longer
referenced in the program.
▪ However, if our program is large and we are reading or writing multiple files that
can take significant amount of resource on the system. If we keep opening new
files carelessly, we could run out of resources. So be a good programmer , close the
file as soon as all task are done with it.

open Function

Before any reading or writing operation of any file, it must be opened first of all. Python
provide built in function open() for it. On calling of this function creates file object for file
operations.

Syntax

file object = open(< file_name >,< access_mode>,< Buffering>)

file_name = name of the file , enclosed in double quotes.

access_mode= Determines the what kind of operations can be performed with


file,like read,write etc.
Buffering = for no buffering set it to [Link] line buffering set it to 1. if it is greater
than 1 ,then it is buffer size. if it is negative then buffer size is system default.

Sr. Mode & Description


No.

1 r - reading only. Sets file pointer at beginning of the file. This is the default
mode.

2 rb – same as r mode but with binary file

3 r+ - both reading and writing. The file pointer placed at the beginning of the
file

4 rb+ - same as r+ mode but with binary file

5 w - writing only. Overwrites the file if the file exists. If not, creates a new file
for writing.

6 wb – same as w mode but with binary file.

7 w+ - both writing and reading. Overwrites . If no file exist, creates a new file
for R & W

8 wb+ - same as w+ mode but with binary file.

9 a -for appending. Move file pointer at end of the [Link] new file for
writing,if not exist.

10 ab – same as a but with binary file.

11 a+ - for both appending and reading. Move file pointer at end. If the file does
not exist, it creates a new file for reading and writing.

12 ab+ - same as a+ mode but with binary mode.

Open a File

Assume we have the following file, located in the same folder as Python:

[Link]

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.


The open() function returns a file object, which has a read() method for reading the
content of the file:

Example

f = open("[Link]", "r")
print([Link]())

If the file is located in a different location, you will have to specify the file path, like
this:

Example

Open a file on a different location:

f = open("D:\[Link]", "r")

print([Link]())

Output:

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify
how many characters you want to return:

Example

Return the 5 first characters of the file:

f = open("D:\[Link]","r")
print([Link](5))
Output:

Hello

Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

f = open("D:\[Link]","r")
print([Link]())
[Link]()
Output: Hello! Welcome to [Link]

Python File Write

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example: "a" - Append - will append to the end of the file

f = open("D:\[Link]","a")
[Link]("Now the file has more content!")
[Link]("Good!")
[Link]()

#open and read the file after the appending:


f = open("D:\[Link]","r")
print([Link]())
Output:

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!
Now the file has more content!Good!
"w" - Write - will overwrite any existing content

f = open("D:\[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()

#open and read the file after the overwriting:


f = open("D:\[Link]", "r")
print([Link]())
Output: Woops! I have deleted the content!

Create a New File

To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example: Create a file called "[Link]":

f = open("[Link]", "x")

print("\n File created successfully")

Result: a new empty file is created!

Example: Create a new file if it does not exist:

f = open("[Link]", "w")

Delete a File

To delete a file, you must import the OS module, and run


its [Link]() function:

Example

Remove the file "[Link]":

import os
[Link]("[Link]")

File Methods

S.N Methods & Description


[Link]()
1
Close the file. A closed file cannot be read or written any more.
[Link]()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-
like objects.
[Link]()
3 Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
[Link]()
4
Returns True if the file is connected to a tty(-like) device, else False.
[Link]()
5
Returns the next line from the file each time it is being called.
[Link]([size])
6 Reads at most size bytes from the file (less if the read hits EOF before obtaining
size bytes).
7 [Link]([size])
Reads one entire line from the file. A trailing newline character is kept in the
string.
[Link]([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the
8 optional sizehint argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.
[Link](offset[, whence])
9
Sets the file's current position
[Link]()
10
Returns the file's current position
[Link]([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
[Link](str)
12
Writes a string to the file. There is no return value.
[Link](sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.

File read() Method

Assume we have the following file, located in the same folder as Python:

[Link]

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the
content of the file:

Example

f = open("[Link]", "r")
print([Link]())

Output: Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!
File readline() Method
Read the first line of the file "[Link]":
f = open("[Link]", "r")
print([Link]())
File readlines() Method
Return all lines in the file, as a list where each line is an item in the list object:
f = open("[Link]", "r")
print([Link]())
File write() Method
Open the file with "a" for appending, then add some text to the file:
f = open("[Link]", "a")
[Link]("See you soon!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
Output:
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
See you soon!
File writelines() Method
Open the file with "a" for appending, then add a list of texts to append to the file:
f = open("[Link]", "a")
[Link](["See you soon!", "Over and out."])
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
Output:
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!See you soon!Over and out.
Splitting words
The split() method splits a string into a list.
You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of
elements plus one.
Syntax
[Link](separator, maxsplit)
Example
Split a string into a list where each word is a list item:
txt = "welcome to II CS"
x = [Link]()
print(x)
Output: ['welcome', 'to', 'II', 'CS']
File Positions or File seek() Method

The seek() method sets the current file position in a file stream.

The seek() method also returns the new postion.

Syntax

[Link](offset)

Parameter Values

Offset Required. A number representing the position to set the current file stream
position.

Change the current file position to 9, and return the rest of the line:

f = open("[Link]", "r")

[Link](9)

print([Link]())

Output: lcome to [Link]

Renaming Files in Python

To rename a file in Python, you can use the [Link]() function. This function takes
two arguments: the current filename and the new filename.

Syntax

[Link](current_file_name, new_file_name)

Parameters

▪ current_file_name − It is the current name of the file you want to rename.


▪ new_file_name − It is the new name you want to assign to the file.
Example

Following is an example to rename an existing file "[Link]" to "[Link]" using


the rename() function –

import os

current_name = "[Link]" # Current file name

new_name = "[Link]" # New file name

[Link](current_name, new_name) # Rename the file

print(f"File '{current_name}' renamed to '{new_name}' successfully.")

Output:

File '[Link]' renamed to '[Link]' successfully.

You might also like