File handling
File handling
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,and1s).
In addition you can specify if the file should be handled as binary or text mode.
"t" - Text -to store character data. Default value. Text mode
"b" - Binary -store data in the form of bytes. Binary mode (e.g. images)
"r" - Read - Default value. Opens a file for reading, error if the file does not exist. F = open(“file.txt”, “r”)
"a" - Append - Opens a file for appending, creates the file if it does not exist. F = open(“file.txt”, “a”)
"w" - Write - Opens a file for writing, creates the file if it does not exist. F = open(“file.txt”, “w”)
"x" - Create - Creates the specified file, returns an error if the file exists. F = open(“file.txt”, “x”)
Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning
of the file. Raises I/O error if the file does not exist. F = open(“file.txt”, “r+”)
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and
over-written. The handle is positioned at the beginning of the file. F = open(“file.txt”, “w+”)
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted at the end, after
the existing data. F = open(“file.txt”, “a+”)
The key function for working with files in Python is the open() function.
create a File
"x" mode is used Create the specified file, returns an error if the file exists
Example:
f = open("C:/Desktop/file.txt", "x")
f.close()
when ever you run above code in python it will create file in desktop with name file.txt .“x” mode is used
to create file and I want to create file in my desktop so you need to given location "C:/Desktop/file.txt"
for example if you want to create file in location: local disk D then just give location “D: /file.txt".
if file.txt is already present then it will display error
whenever you open a file, at last you need to close file by using close() function
1.Open() a File
Syntax
To open a file for reading it is enough to specify the name of the file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
f = open("file.txt")
Assume we have the following file, located in the Desktop, let file name is file.txt , let file contains text
given below:
file.txt
Good Luck!
Example
f = open("C:/Desktop/file.txt", "r")
print(f.read())
f.close()
output:
Good Luck!
In the above example,I want to open file which is present in my desktop so you need to specify path like
“C:/Desktop/file.txt”. If the file is located in a different location, you will have to specify the file path.
I want to read text present in file.txt . so , I am using “r” mode to read text present in file named file.txt ,
by using read mode you can only read a file .
read( ) function is used to read text present in my file and print( ) function is used to print text on my
output screen so I written print(f.read()).
whenever you open a file, at last you need to close file by using close() function.
Note: Make sure the file exists, or else you will get an error.
Example2:
f = open("C:/Desktop/file.txt", "r")
print(f.read(5))
f.close()
output:
Hello
In above example I written print(f.read(5)) so it will print only first 5 characters. So ,I will get output hello
whenever you open a file, at last you need to close file by using close() function.
3.readline() method :
Assume we have the following file, located in the Desktop, let file name is file.txt , let file contains text
given below:
File.txt
Good Luck!
Output:
f = open("C:/Desktop/file.txt", "r")
print(f.readline())
f.close()
output
By calling readline() two times, you can read first two lines.
readlines() method:
Assume we have the following file, located in the local disk E, let file name is sai.txt , let file contains
text given below:
file.txt
hello shubh
i am syra
i am from shimla
program:
a=open("E:/sai.txt","r")
print(a.readlines())
a.close()
output:
Python FileWrite
To write to an existing file, you must add a parameter to the open() function:
Assume we have the following file, located in the Desktop, let file name is file.txt , let file contains text
given below:
This is shubh
Good Luck!
Program: to add text “ how are you ? “ at last in my file named file.txt
f.close()
f.close()
output:
This is shubh
Good Luck!
f.close()
f.close()
output:
From above example, “w” mode will replace text with ” how are you?
f.close()
output:
From above example, “w” mode will replace text with ” how are you?”
f.writelines([‘hello\n’,’world\n’])
f.seek(0)
f.tell()
truncate() Method :
For example, my file name is file.txt and my file contains data i.e., hello india
The truncate() method resizes the file to the given number of bytes.If the size is not specified, the current
position will be used.
Syntax
file.truncate(size)
Example
Open the file with "a" for appending, then truncate the file to 5 bytes: a= open("file.txt", "a")
a.truncate(5)
a.close()
#open and read the file after the truncate: a= open("file..txt", "r")
print(a.read())
output: hello
flush() Method:
Syntax f.flush()
example:
a= open("myfile.txt", "a")
a.flush()
a.write("hello")
Note:-Position=Form all the above examples for each and every method you need to include f.close(),
f.read(), f.write(), f.readline()….so on. Because my file is present in variable f. So you need to include
variable_name before any method.
file object attributes
Once a file is opened and you have one file object, you can get various information related to that file.
1 file.closed
2 file.mode
3 file.name
In a computer, a file system is the way in which files are named and where they are placed logically for
storage and retrieval.
Python OS module provides the facility to establish the interaction between the user and the operating
system. It offers many useful OS functions that are used to perform OS-based tasks and get related
information about operating system.
Python’s OS module comes packaged within python when installed. This means you do not need to
separately install it In order to access its various methods/functions, you just need to import the module.
import os
Now that you’ve imported the module, you can start using its various functions.
The currently working directory is the folder in which the python script is saved and being run from.
Program:
import os os.getcwd()
output:
D:\ Python\
Creating a directory:
import os
os.mkdir("D:\syra")
Note − If no location is specified, it will just create a “new folder” in the current working directory.
Deleting a directory
In order to delete a directory, we will be using the rmdir() function, it stands for remove directory.
import os os.rmdir("D:\syra")
Renaming a directory
In order to rename a folder, we use the rename function present in the os module.
import os
os.mkdir("D:\ syra")
os.rename("D:\syra","D:\syra2")
The os module provides the chdir() function to change the current working directory.
import os os.chdir("d:\\")
To get the list of all files and directories in the specified directory
os.listdir() method in python is used to get the list of all files and directories in the specified directory.
program:
import os
os.listdir("D:/syra")
output:
[ 'file.txt, 'image.jpeg’, 'New folder']
above code will display files/ folder present in syra directory which is located in local disk D
In syra directory which is located in local disk D contains 3 files file.txt, image.jpeg and New folder. It
will display output in to form of list
Program To get the list of all files and directories in the specified directory Line by line
program: import os
a=os.listdir("D:/syra")
for i in a:
print(i)
output:
file.txt
image.jpeg
New folder
os.system() method:
os.system("notepad")
output: 0
0 means success so, when you run above code it will automatically opens notepad if output is 0
The process to converts any kind of python objects (list, dict, tuple etc.) into byte streams (0s and 1s) is
called pickling or serialization or flattening or marshalling. We can converts the byte stream (generated
through pickling) back into python objects by a process called as unpickling or de-serializing.
In real world sceanario, the use pickling and unpickling are widespread as they allow us to easily
transfer data from one server/system to another and then store it in a file or database.
Python pickle module is used for serializing and de-serializing python object
Only after importing pickle module we can do pickling and unpickling. Importing pickle can be done
using the following command –
import pickle Example:
b=open(“D:/newfile.txt” , ”wb”)
pickle.dump(a,b)
f= open(“D:/newfile.txt” , ”rb”)
print(pickle.load(f))
From the above example I want to store list object to file named newfile.txt so I took list in variable “a”
and newfile.txt in “b” and we need to use “wb” mode i.e., write binary because I want to copy list
object to my file named newfile.txt and when you write pickle.dump(a,b) this pickle.dump() method
will copy list object present in variable “a” to “b” i.e, newfile.txt
If you want to print data which is present in newfile.txt you need to use pickle.load( ) method. Here you
need to use “rb” mode i.e., read mode because I want to read data which is present in newfile.txt. so I
will get output [‘syra’,10,’btech’] which is present in newfile.txt.
Marshal Module
Even though marshal module in Python’s standard library provides object serialization features (similar
to pickle module), it is not really useful for general purpose data persistence or transmission of Python
objects through sockets etc.
Difference between marshal and pickle is that marshal can handle only simple python objects
(numbers,sequences,mapping) while pickle can handle all types of objects including classes.
Just as pickle module, marshal module also defined load() and dump() functions for reading and writing
marshaled objects from / to file.
dumps() − method is used to pickle objects. Only objects of standard data types are supported for
pickling. Unsupported types raise ValueError exception.
loads() − method is used to un-pickle objects. If the conversion doesn’t result in valid Python object,
ValueError or TypeError may be raised.
Example:
output:
[‘syra’,10,’btech’]
Shelve Module
The Shelve Module of Python is a very popular module of Python which works like an effective tool for
persistent data storage inside files using a Python program. As the name of this module suggests, i.e.,
Shelve, we can easily interpret that it will work as a shelf object to keep all our data inside a file and save
all the necessary information.
Shelve Module is not only helpful in storing information inside a file, but it is also very effective in
modifying the already present information and adding some new information in the same file. We can
perform all these operations (creating, reading, writing, and deleting from a file) from the Shelve Module
by using this module and its functions inside a Python program.
This will create test.dir file in local lisk D and store key-value data in hashed form. The Shelf object has
following methods available −To access value of a particular key in shelf −
print (list(a.items()))
print (list(a.keys()))
print (list(a.values()))