0% found this document useful (0 votes)
2 views

File handling

The document provides a comprehensive overview of file handling in Python, detailing various file modes, methods for reading and writing files, and the importance of closing files. It also introduces the Python OS module for file system interactions and discusses persistent storage modules like Pickle, Marshal, and Shelve for data serialization. Key functions and examples are provided to illustrate how to create, read, write, and manipulate files effectively in Python.

Uploaded by

Priksha Sharma
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)
2 views

File handling

The document provides a comprehensive overview of file handling in Python, detailing various file modes, methods for reading and writing files, and the importance of closing files. It also introduces the Python OS module for file system interactions and discusses persistent storage modules like Pickle, Marshal, and Shelve for data serialization. Key functions and examples are provided to illustrate how to create, read, write, and manipulate files effectively in Python.

Uploaded by

Priksha Sharma
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
You are on page 1/ 14

Files

File handling is an important part of any web application.

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)

Python File Modes

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. 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.

The open() function takes two parameters; filename, and mode.

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

File built In methods

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")

The code above is the same as: f = open("file.txt", "r")

To print text present in my file on output :

Assume we have the following file, located in the Desktop, let file name is file.txt , let file contains text
given below:

file.txt

Hello! Welcome to python world!

Good Luck!

2.read() method for reading the content of the file:

Example

f = open("C:/Desktop/file.txt", "r")

print(f.read())

f.close()

output:

Hello! Welcome to python world!

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 :

You can return one line by using the 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

Hello! Welcome to python world!

This is programming platform.

Good Luck!

Output:

f = open("C:/Desktop/file.txt", "r")

print(f.readline())

f.close()

output

Hello! Welcome to python world!

By calling readline() two times, you can read first two lines.

readlines() method:

Returns a list of lines from the file.

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:

['hello shubh\n', 'i am syra \n', 'i am from shimla\n']

Python FileWrite

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

Assume we have the following file, located in the Desktop, let file name is file.txt , let file contains text
given below:

Hello! Welcome to Shimla.

This is shubh

Good Luck!

Program: to add text “ how are you ? “ at last in my file named file.txt

f = open("C:/Desktop/file.txt ", "a") #use “a” mode to add text

f.write("how are you ? “)

f.close()

open and read the file after the appending:

f = open("file.txt", "r") # use “r” mode to print data as output

print(f.read()) #print( ) function to print output

f.close()

output:

Hello! Welcome to Shimla.

This is shubh

Good Luck!

how are you?


"w" - Write - will overwrite any existing content

f = open("file.txt", "w") #use “w” mode to add text to my file

f.write("how are you ? “)

f.close()

#open and read the file after the appending:

f = open("file.txt", "r") # use “r” mode to print data as output

print(f.read()) #print( ) function to print output

f.close()

output:

how are you?

From above example, “w” mode will replace text with ” how are you?

#open and read the file after the appending:

f = open("file.txt", "r") # use “r” mode to print data as output

print(f.read()) #print( ) function to print output

f.close()

output:

how are you?

From above example, “w” mode will replace text with ” how are you?”

Writelines()- write a list of strings to the files.

f.writelines([‘hello\n’,’world\n’])

Seek()-change the file current position.

f.seek(0)

Tell()-shows the current cursor position.

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:

The flush() method cleans out the internal buffer.

Syntax f.flush()

example:

a= open("myfile.txt", "a")

a.write("how are you")

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.

Here is a list of all attributes related to file object −

SR.NO. ATTRIBUTE & DESCRIPTION

1 file.closed

Returns true if file is closed, false otherwise.

2 file.mode

Returns access mode with which file was opened.

3 file.name

Returns name of the file.


File system : Python OS Module

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.

Getting current working directory Note − Directory is nothing but folder.

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\

Note − Directory is nothing but folder.

Creating a directory:

import os

os.mkdir("D:\syra")

This will create a folder syra in the D drive.

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 above line of code renames syra to syra2.

change the current working directory:

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:

used to open files present in system like notepad, chrome etc….

os.system("notepad")

output: 0

0 means success so, when you run above code it will automatically opens notepad if output is 0

It returns 1 if it fails to open particular file.

Persistent storage modules Pickle Module

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

pickle.dump ( ) method is used to pickle objects

pickle.load ( ) method is used to un-pickle objects

Only after importing pickle module we can do pickling and unpickling. Importing pickle can be done
using the following command –
import pickle Example:

Import pickle a=[“syra”,10,”btech”]

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.

marshal.dump ( ) method is used to pickle objects

marshal.load ( ) method is used to un-pickle objects

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:

Import marshal a=[“syra”,10,”btech”]

b=marshal.dumps(a) #marshal.dumps() will copy list ‘a’ to ‘b’

marshal.loads(b) #marshal.loads() will print output present in ‘b’

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.

Following code creates a database and stores dictionary entries in it.

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()))

output: [('name', 'Ajay'), ('age', 25), ('marks', 75)]

print (list(a.keys()))

output: ['name', 'age', 'marks']

print (list(a.values()))

output: ['Ajay', 25, 75]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy