0% found this document useful (0 votes)
10 views45 pages

Python File Handling and Operations Guide

The document provides an overview of file handling in Python, covering the creation, reading, writing, and manipulation of text and binary files using built-in functions and the os module. It explains various file modes, methods for reading and writing data, and how to manage directories. Additionally, it discusses command line arguments, file copying with the shutil module, and merging files into a new file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views45 pages

Python File Handling and Operations Guide

The document provides an overview of file handling in Python, covering the creation, reading, writing, and manipulation of text and binary files using built-in functions and the os module. It explains various file modes, methods for reading and writing data, and how to manage directories. Additionally, it discusses command line arguments, file copying with the shutil module, and merging files into a new file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Files

• 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 and 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.
• To open a file, we need to use the built-
in open function. The Python file open function
returns a file object that contains methods and
attributes to perform various operations for
opening files in Python.
Syntax of Python open file function
file_object = open("filename", "mode")
Here,
• filename: gives name of the file that the file object
has opened.
• mode: attribute of a file object tells us which
mode a file was opened in.
• There are four different methods (modes) for opening a file:
• "r" - Read - Default value. Opens a file for reading, error if
the file does not exist
• "a" - Append - Opens a file for appending, creates the file if
it does not exist
• "w" - Write - Opens a file for writing, creates the file if it
does not exist
• "x" - Create - Creates the specified file, returns an error if
the file exists
• In addition you can specify if the file should be handled as
binary or text mode
• "t" - Text - Default value. Text mode
• "b" - Binary - Binary mode.
Syntax
• To open a file for reading it is enough to
specify the name of the file:
f = open("[Link]")
• The code above is the same as:
f = open("[Link]", "rt")
• 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!
• The open() function returns a file object, which
has a read() method for reading the content of the
file:
Ex:
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:
Ex:
• Open a file on a different location:
f = open("D:\\myfiles\ece\[Link]", "r")
print([Link]())
• By default the read() method returns the whole text, but
you can also specify how many characters you want to
return:
Ex:
• Return the 5 first characters of the file:
f = open("[Link]", "r")
print([Link](5))
• We can return one line by using the readline() method:
Ex:
• Read one line of the file:
f = open("[Link]", "r")
print([Link]())
• By calling readline() two times, you can read the two
first lines:
Ex:
• Read two lines of the file:
f = open("[Link]", "r")
print([Link]())
print([Link]())
• By looping through the lines of the file, you
can read the whole file, line by line:
Ex:
• Loop through the file line by line:
f = open("[Link]", "r")
for x in f:
print(x)
• To write to an existing file, we 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
Ex:
• Open the file "[Link]" and append
content to the file:

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

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
• Open the file "[Link]" and overwrite
the content:

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

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
• 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
Ex:
• Create a file called "[Link]":
f = open("[Link]", "x")
• Result: a new empty file is created!
Ex:
• Create a new file if it does not exist:
f = open("[Link]", “r")
• We can change our current file cursor (position) using
the seek() method. Similarly, the tell() method returns our
current position (in number of bytes).
Ex:
[Link]() # get the current file position
56
[Link](0) # bring file cursor to initial position
0
print([Link]()) # read the entire file

This is my first file


This file
contains three lines
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
• To use this module you need to import it first
and then you can call any related functions.
rename() Method
• The rename() method takes two arguments,
the current filename and the new filename.
Syntax:
[Link](current_file_name, new_file_name)
remove() Method
• We can use the remove() method to delete
files by supplying the name of the file to be
deleted as the argument.
Syntax
[Link](file_name)
• All files are contained within various directories.
The os module has several methods that helps
us create, remove, and change directories.
mkdir() Method
• We can use the mkdir() method of
the os module to create directories in the
current directory. We need to supply an
argument to this method which contains the
name of the directory to be created.
Syntax
[Link]("newdir")
chdir() Method
• We can use the chdir() method to change the current directory. The
chdir() method takes an argument, which is the name of the directory
that you want to make the current directory.
Syntax
[Link]("newdir")
getcwd() Method
• The getcwd() method displays the current working directory.
Syntax
[Link]()
rmdir() Method
• The rmdir() method deletes the directory, which is passed as an
argument in the method.
• Before removing a directory, all the contents in it should be removed.
Syntax
[Link]('dirname')
Format operator
• The built-in format() method returns a formatted
representation of the given value controlled by the format
specifier.
• The format() function is similar to the String format method.

The syntax of format() is:


format(value[, format_spec])
• The format() function takes two parameters:
value - value that needs to be formatted
format_spec - The specification on how the value should be
formatted.
Ex: Number formatting with format()
# d, f and b are type

# integer
print(format(123, "d"))

# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))
Output:
123
123.456790
1100
Printf(“%d”,a);
• A format sequence can appear anywhere in the
string, so we can embed a value in a sentence.
Ex:
camels = 42
'I have spotted %d camels.‘ % camels
O/p:
'I have spotted 42 camels.‘
• If there is more than one format sequence in the string, the
second argument has to be a tuple. Each format sequence is
matched with an element of the tuple, in order.
• 'In %d years I have spotted %f %s.' % (3, 0.1, 'camels')
O/p:
'In 3 years I have spotted 0.1 camels.‘

• The number of elements in the tuple has to match the number of


format sequences in the string. Also, the types of the elements
have to match the format sequences:

• '%d %d %d' % (1, 2)


• TypeError: not enough arguments for format string
• '%d' % 'dollars'
• TypeError: illegal argument type for built-in operation
Filenames and paths
• Files are organized into directories (also called “folders”). Every running program has a

“current directory,” when you open a file for reading, Python looks for it in the current

directory.

• The os module provides functions for working with files and directories (“os” stands for

“operating system”). [Link] returns the name of the current directory:

• A string like cwd that identifies a file is called a path. A relative path starts from the current

directory; an absolute path starts from the topmost directory in the file system.

• To find the absolute path to a file, we can use [Link]

• [Link]('[Link]')
• [Link] checks whether a file or directory exists or not.
[Link]('[Link]')
O/p True
• If it exists, [Link] checks whether it’s a directory or not.
[Link]('[Link]')
O/p False
[Link]('music')
O/p True
• Similarly, [Link] checks whether it’s a file or not.
[Link] returns a list of the files (and other directories) in the
given directory:
[Link](cwd)
['music', 'photos', '[Link]']
Command line arguments
• To read data from the user we can use input().
• But we have another method also to read data from the
user instead of input().
• In this new method, inputs will be passed to the program
as an arguments from the command prompt.
• For these processing of inputs from the command prompt,
we use sys module.
• All the inputs which are passed through a command
prompt are forms like a list as argv.
• All these inputs which are present in argv can be accessed
by using [Link]
• Elements of [Link] can be placed like a list.
• And all these elements of argv are accessed by
using index positions.
• Just like array, all these elements index
position is also starts with 0.
• But 0th position of argv must be a filename.
Remaining all index positions contains input
values.
Ex:
import sys
print([Link])

It provides output as a list of elements.


Ex:
import sys
print([Link])
# returns total count of arguments including with filename
len([Link])

To execute this program perform the following steps:


• Write program
• Save with .py extension
• Open command prompt
• Change the path to where the program is being saved
• Py [Link] arg1 arg2 arg3 ……..
import sys
for i in range(len([Link])):
sum+=[Link][i]
printf(“result=“sum)
• Python has a set of methods available for the file object.

close() Closes the file


read() Returns the file content
readable() Returns whether the file stream can be
read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or
not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
• If the total number of bytes returned exceeds the
specified number, no more lines are returned.
• The truncate() method resizes the file to the
given number of bytes.

f = open("[Link]", "a")
[Link](20)
[Link]()

#open and read the file after the truncate:


f = open("[Link]", "r")
print([Link]())
• The writelines() method writes the items of a
list to the file.

f = open("[Link]", "a")
[Link](["See you soon!", "Over andout."])
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
Copying files
Shutil module in Python provides many functions of high-
level operations on files and collections of files. It comes
under Python’s standard utility modules. This module
helps in automating the process of copying and removal
of files and directories.
What is [Link]() method in Python
The [Link]() method in Python is used to copy the
content of the source file to the destination file.
Source and destination must represent a file and
destination must be writable. If the destination already
exists then it will be replaced with the source file
otherwise a new file will be created.
Syntax: [Link](source, destination, *,
follow_symlinks = True)
Parameter:
source: A string representing the path of the
source file.
destination: A string representing the path of the
destination file.
follow_symlinks (optional) : The default value of
this parameter is True. If False and source
represents a symbolic link then a new symbolic
link will be created instead of copying the file.
Example 1: Use of [Link]() method to copy a
file from source to destination

# Python program to explain [Link]() method

# importing os module
import os

# importing shutil module


import shutil

# path
path = '/home/User/Documents'

# List files and directories in '/home/User/Documents'


print("Before copying file:")
print([Link](path))
# Source path
source = "/home/User/Documents/[Link]"

# Destination path
destination = "/home/User/Documents/file(copy).txt"

# Copy the content of source to destination


dest = [Link](source, destination)

# List files and directories in "/home / User / Documents"


print("After copying file:")
print([Link](path))

# Print path of newly created file


print("Destination path:", dest)
Output
• Before copying file: ['[Link]', '[Link]',
'[Link]', '[Link]', '[Link]']
• After copying file: ['[Link]', '[Link]',
'[Link]', '[Link]', 'file(copy).txt',
'[Link]']
• Destination path:
/home/User/Documents/file(copy).txt
Python Program to merge two files into a third
file

• Let the given two files be [Link] and [Link]. Our


Task is to merge both files into third file say [Link].
The following are steps to merge.
• Open [Link] and [Link] in read mode.
• Open [Link] in write mode.
• Read the data from file1 and add it in a string.
• Read the data from file2 and concatenate the data of
this file to the previous string.
• Write the data from string to file3
• Close all the files
# Python program to demonstrate merging of two files
Ex 1:

data = data2 = ""

# Reading data from file1


with open('[Link]') as fp:
data = [Link]()

# Reading data from file2


with open('[Link]') as fp:
data2 = [Link]()
# Merging 2 files To add the data of file2 from
next line
data += "\n"
data += data2

with open ('[Link]', 'w') as fp:


[Link](data)
Ex 2:
filenames = ['[Link]', '[Link]', '[Link]']
with open('output_file', 'w') as f1:
for fname in filenames:
with open(fname) as f2:
[Link]([Link]())
program to count the given character in a
file
Method : Using the in-built count() method.
Approach:
• Read the file.
• Store the content of the file in a variable.
• Use the count() method with the argument as
a letter whose frequency is required.
• Display the count of the letter.
# Program to get letter count in a text file

# explicit function to return the letter count


def letterFrequency(fileName, letter):
# open file in read mode
file = open(fileName, 'r')

# store content of the file in a variable


text = [Link]()
# using count()

return [Link](letter)

# call the function and display the letter count

print(letterFrequency('[Link]', 'g'))

You might also like