Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Unit-IV Python_BCC402 (File Handling)

Python Unit 4 notes.

Uploaded by

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

Unit-IV Python_BCC402 (File Handling)

Python Unit 4 notes.

Uploaded by

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

PYTHON PROGRAMMING

UNIT-IV
@Dr. Shankar Thawkar
Introduction to File Handling in Python

 A file is a collection of data stored on a secondary storage device.


 Files are named locations on disk to store related information. They are used to store
data permanently in a non-volatile memory (e.g. hard disk).
 Since Random Access Memory (RAM) is volatile (which loses its data when the
computer is turned off), files are used for future use of the data by permanently storing
them.
 To read from or write to a file, it needs to be opened first. When operation is done, it
needs to be closed so that the resources that are tied with the file are freed.
 Hence, in Python, a file operation takes place in the following order:
• Open a file
• Read or write (perform operation)
• Close the file

@Dr. Shankar Thawkar


Relative path and absolute path
• An absolute path is defined as specifying the location of a file or directory from the root
directory(/).
• In other words, an absolute path is a complete path from start of actual file system from /
directory.

• Relative path- Relative path is defined as the path related to the current working
directly(cwd). It starts at your current directory and never starts with a / .

@Dr. Shankar Thawkar


Types of files that can be handled in python

• Python provides inbuilt functions for creating, writing and reading files.
• There are two types of files that can be handled in python:
• Normal text files
• Binary files (written in binary language,0s and 1s).

Text files:
In this type of file, Each line of text is terminated with a special character called EOL (End of
Line), which is the new line character (‘\n’) in python by default.

Binary files:
In this type of file, there is no terminator for a line and the data is stored after converting it into
machine understandable binary language.

@Dr. Shankar Thawkar


Opening and closing file

• The key function for working with files in Python is the open() function.

• The open() function takes two parameters


• filename
• mode.
Syntax
• To open a file for reading it is enough to specify the name of the file:
f = open(“Myfile.txt")
• The code above is the same as:
f = open(“Myfile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.

@Dr. Shankar Thawkar


Access Modes
mode Description

“r” Read - Default value. Opens a file for reading, error if the file does not exist

“w” Write - Opens a file for writing, creates the file if it does not exist

“a” Append - Opens a file for appending, creates the specified file if it does not exist

“x” Create - Creates the specified file, returns an error if the file exists

“t” Text - Default value. Text mode

“b” Binary - Binary mode (e.g. images)

@Dr. Shankar Thawkar


Closing file
• 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(“Myfile.txt", "r")
print(f.read()) Myfile.txt
f.close()

Note: You should always close your files, Hello! Welcome to Myfile.txt
in some cases, due to buffering, changes This file is for testing
made to a file may not show until you close purposes.
the file.
Good Luck!

@Dr. Shankar Thawkar


Reading & writing file
• The open() function returns a file object, which has a read() method for reading the
content of the file:
Example
f = open(“Myfile.txt", "r")
print(f.read())
f.close() Myfile.txt
Output: Hello! Welcome to Myfile.txt
Hello! Welcome to
Myfile.txt
This file is for testing
This file is for testing purposes.
purposes. Good Luck!
Good Luck!

@Dr. Shankar Thawkar


Reading & writing file
• 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(“Myfile.txt", "r") Myfile.txt


print(f.read(5))
f.close() Hello! Welcome to Myfile.txt
Output: Hello
This file is for testing
purposes.
Good Luck!

@Dr. Shankar Thawkar


Read Lines
• You can return one line using readline() method:
Example:
f = open(“Myfile.txt", "r")
print(f.readline())
f.close()
Output: Hello! Welcome to

• Calling readline() 2 times, makes reading of first 2 lines: Myfile.txt


Example:
f = open(“Myfile.txt", "r")
print(f.readline()) Hello! Welcome to Myfile.txt
print(f.readline()) This file is for testing
f.close() purposes.
Output:
Hello! Welcome to Good Luck!
@Dr. Shankar Thawkar
Myfile.txt
Read Lines
• By looping through the lines of the file, you can read the whole file, line by line:

Example
Loop through the file line by line:

f = open(“Myfile.txt", "r") Myfile.txt


for x in f:
print(x) Hello! Welcome to Myfile.txt
This file is for testing
purposes.
Good Luck!

@Dr. Shankar Thawkar


Write to an Existing File

Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!

Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")

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

@Dr. Shankar Thawkar


writing to an Existing File-append mode
Example:
Open the file “Myfile2.txt" and append content to the file:
f = open(“Myfile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

Output:
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content!

@Dr. Shankar Thawkar


Write to an Existing File
Example:
Open the file "demofile3.txt" and overwrite the content:
f = open("Myfile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

Output:
Woops! I have deleted the content!
Note: the "w" method will overwrite the entire file.
@Dr. Shankar Thawkar
Write to an Existing File
• write() method is used to write a string to an already opened file.
• Strings may include numbers, special characters or other symbols.
• write() method does not add a newline(‘\n’) character to the end of
string.

Syntax:
file.write(string)

@Dr. Shankar Thawkar


Write to an Existing File
• writelines() method is used to write a list of strings.
• Program to write a file using writelines() method

f=open(“Myfile.txt”,”w”);
lines=[“Hello world”, “Welcome to python”, “Enjoy Python”]
f.writelines(lines)
f.close()
print(“Data written to file”)

Output:
Data written to file
@Dr. Shankar Thawkar
Opening file using with keyword
• When a file is open using with keyword it is closed implicitly
(automatically) after use.

# Python code to illustrate with keyword


with open(“Myfile.text", "r") as file:
print(file.read())

@Dr. Shankar Thawkar


File Positions
• A pointer is associated with every file, called file pointer.
• File pointer is used for the movement across the file during read/write operation.
• The file pointer specifies the location from where current read/write operation is initiated.
• Python support the function called seek() to set the position of file pointer.
• It has following syntax:
Seek(offset[,from])
• The offset argument indicate the number of bytes to be moved and the from argument
specifies the reference position from where the bytes are to be moved.
• Following table specifies the value of from argument-
From Reference position

0 From the beginning of file


1 From current position
2 From the end of file
@Dr. Shankar Thawkar
Example File Positions
f = open(“Myfile.txt", "r")
print(f.read(10))
f.seek(3,1) # move 3 bytes from current position
print(f.read(10))
print(f.read())
f.close()

@Dr. Shankar Thawkar


split() using file handling
• We can also split lines using file handling in Python. This splits the
variable when space is encountered. You can also split using any
characters as we wish. Here is the code:
# Python code to illustrate split() function
file=open(“Myfile.text", "r")
data = file.readlines()
for line in data:
word = line.split()
print(word)
@Dr. Shankar Thawkar
Program to rename file1.txt to student.txt
import os
os.rename(“file1.txt”, “sudent.txt”)
Print(“File renamed”)

Output:
File renamed

@Dr. Shankar Thawkar


Delete files
• remove() method:
• This method can be used to delete file. Filename needs to be
passed as argument.

import os
os.remove (“file1.txt”)
print(“File deleted”)

Output:
File deleted
@Dr. Shankar Thawkar
Assignment
• Write a program that read text from a file and write into another
file.
• Write a program that copy one file into another.
• Write a program that read a text file and display number of
vowels in a file.
• Write a program that read text from a file and write into another
file but in reverse order.

@Dr. Shankar Thawkar


@Dr. Shankar Thawkar

You might also like