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

File Handling Notes

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)
20 views

File Handling Notes

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/ 6

Grade 12: FILE HANDLING Subject: Computer Science

FILE HANDLING – TEXT FILES

I. INTRODUCTION:

• Files are named locations on disk to store related information. They are used to permanently store data in a non-
volatile memory (e.g. hard disk).

In Python, a file operation takes place in the following order:

– Open a file

– Read or write (perform operation)

– Close the file

Types of File in Python

1) Binary file

2) Text file

Text files in Python

• A text file is usually considered as sequence of lines. Line is a sequence of characters (ASCII), stored on permanent
storage media.

• In text file, each line is terminated by a special character, known as End of Line (EOL). From strings we know that \n
is newline character.

• At the lowest level, text file is collection of bytes. Text files are stored in human readable form. They can also be
created using any text editor.

• Text files don’t have any specific encoding and it can be opened in normal text editor itself.

html, XML, CSS,


Web standards
JSON

c, app, js, py,


Source code
java etc.

Text files Documents txt, tex, RTF etc.

Tabular data csv, tsv etc.

Configuration : ini, cfg, reg etc

III. OPENING OR CREATING A NEW FILE IN PYTHON

• The method open() is used to open an existing file or creating a new file. If the complete directory is not given then
the file will be created in the directory in which the python file is stored.
<file_object name>= open( <file_name>, <access mode>)
<file_object name>= open( r <file_name>, <access mode>)
The prefix r makes it a raw string specifies no special meaning attached to any character

with open(<file name>,<access mode>) as <file_object name>


no need to close the file. It will automatically close the file.

Examples of Opening TEXT Files in Python

# open file in current directory f = open("test.txt“, “r”)

# specifying full path as raw string f = open(r“D:\temp\data.txt“, “r”) #–raw string

#absolute path f = open(“D:\\temp\\data.txt“, “r”)

#automatically closes the file with open(“D:\\temp\\data.txt“, “r”) as f

ACCESS MODES

Default mode for file opening in “r” read mode. If we didn’t specify mode during the
openingof the file then it will automatically open the file in read mode.

Access Access Access Description File


Mode for Mode Mode Pointer(offset)
TextFiles for for CSV Position
Binary Files
Files
r rb r Read mode. Opens a file for reading.If the file does not Beginning of
exist, open() raises a FileNotFoundError. File
r+ rb+ It opens the file for both reading and writing. If the file Beginning of
does not exist, open()raises a FileNotFoundError. File
w wb w Write mode. It opens the file for writingonly. If the file Beginning of
exists, the content of thefile will be removed. If the file File
does not exist, it is created.

w+ wb+ The w+ mode opens the file for both writing and Beginning of
reading. Like w, if the file exists, then the content of the File
file will be removed. If the file does not exist, it is
created.

a ab a The a mode opens the file forappending. In this the End of File
new content is added after the existing content. If the
file does not exist, it creates the new file.

a+ ab+ The a+ mode opens the file for both appending and End of File
reading. In this the new content is added after the
existingcontent. If the file does not exist, it is created.

CLOSING FILES IN PYTHON

• After processing the content in a file, the file must be saved and closed.

<file_object>.close()
READING FILES IN PYTHON

• In order to read a file in python, we must open the file in read mode.

• There are three ways in which we can read the files in python.

– read([n]) # n is the number of bytes to be read.

– readline([n]) # n is the number of bytes to be read.

– readlines() # all lines returned to a list

• All these read function also read leading and trailing whitespaces, new line characters. If we want to remove these
characters you can use functions

– strip() : removes the given character from both ends.

– lstrip(): removes given character from left end

– rstrip(): removes given character from right end

WRITE TO A PYTHON TEXT FILE

• In order to write data into a file, we must open the file in write mode.

• We need to be very careful while writing data into the file as it overwrites the content present inside the file that
we are writing, and all the previous data will be erased.

• We have two methods for writing data into a file as shown below.

If the file doesn’t exist then it will create the file.


1. write( ): It takes string as an input and writes it into the file.
a. Syntax: file_object.write(string)
b. i.e. f.write(“Hello World”)

2. writelines( ): It is used to write multiple lines as a list of strings into the file. In
this eachelement of the list will be treated as a separate line in the file.
a. Syntax: file_object.writelines(list of strings)
b. data=[“I am a student of DOE”, “I studies in class 12th”]
f.writelines(data)
FILE POINTER

• Every file maintains a file pointer which tells the current position in the file where reading and writing operation
will take.

• When we perform any read/write operation two things happens:

– The operation at the current position of file pointer

– File pointer advances by the specified number of bytes.

Method Syntax Description

seek( ) Syntax: seek() function is used to change the


<file_object>.seek(<offset>,<from_where>) position of the File Handle to a given
specific position. File handle is like a
where: cursor, which defines from where the
offset: number of positions to be more forward data has to be read or written inthe file.

from_where: it defines to reference point


Then it returns the new absolute position.i.e.
f.seek(10,0) 0: sets the reference point at the
beginning of the file. (default)
Here, f is the file handle, 10 is the offset (it moves
the cursor 10 bytes forward), 0 means reference 1: sets the reference point at thecurrent
point at the beginning of file. file position.
2: sets the reference point at the endof
the file

Note: In the case of a text file we canuse


only ‘0’ as a reference point.

tell( ) Syntax: <file_object>.tell( ) tell() function returns the current


i.e. position of the file object. This method
takes no parameters and returns an
position=f.tell( ) integer value. Initially thefile pointer
Here, position will hold the integer value of the file points to the beginning of the file(if not
pointer returned by tell function. opened in append mode). So, the initial
value of tell() iszero.
f is the file handle.

WORKING IN BINARY FILES:


Pickle module: pickle module is used in binary file for load( ) and dump( ) methods which are used for reading and
writing into binary file respectively.

Pickling: It is the process of converting python object into byte stream. Pickling is done at the time of writing into a
binary file.

Unpickling: It is the process of converting a byte stream into python object. Unpickling is done at the time reading
from a binary file.

dump( ): it is used to write data into binary file.

Syntax: identifier = pickle.dump(data , file_pointer)

Example:

a= “My name is Anuj”


pickle.dump(a,f) #where ‘a’ contains data and ‘f’ is a file pointer.

load( ): it is used to read data from binary file.


Syntax: identifier = pickle.load(file_pointer)

Example:
data = pickle.load(f) #Here ‘data’ is an identifier and ‘f’ is a file pointer.
COMMA SEPARATED VALUE (CSV) FILES:
• It is a plain text file which stores data in a tabular format, where each row represents a record and each
column represents a field and fields are separated by comma in csv files.
• File extension for csv file will be .csv

csv module is used for working with csv files


import csv
CSV module provides two main classes for working with csv files are:
a. reader b. writer
CSV reader object can be used to iterate through the rows of the CSV file.
CSV writer object that can be used to write row(s) to the CSV file.
We can read csv file data in excel file also.

Reader Function:
For reading data from csv file we require csv. reader( ) function.
Writer Function:
For writing data to the csv file we take a file object as input and write the data into the file.
writerow( ): It writes a single row of data to the CSV file.
writerows( ): It writes a list of rows of data to the CSV file.

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