Vous êtes sur la page 1sur 8

File Handling

Python File I/O


 What is a file?
 What is file handling?
 Open a file
 Read or write (perform operation)
 Close the file
 Directory operations: To open any kind of file we need to first go to that
particular path where the directory is located and then create a file in
that particular path.
os is one kind of internal module in python which performs operating
system related functionalities.
1. removing dir if exists - rmdir() #removes only empty directory
2. check current dir- getcwd()
3. change dir-chdir()
4. Rename Dir-rename()
5. list current dir-listdir()
How to open a file?
Python has a built-in function open() to open a file. 
Syntax:
file_obj = open(<file_name>, <mode>) , where mode
= r,w,a,r+,w+,a+
*The default is reading in text mode.
*binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.

Operation mode Read Write Append(adding new data to the existing


r ,rb w,wb data in a file)
a,ab
Open when file Error Create new Create new file
doesn’t exist file
Open when file exist Opens the file Create new Open for appending the data
file
Cursor position Beginning Beginning Last
Functions/operations Read(),readlin Write() Write()
es()
Write content to the file : write()
Syntax:
file_obj = open(<file_name>, ‘w’)
file_obj.write(“some string”)

Read content from the file: read(), readlines()


Syntax:
file_obj=open(<file_name>,'r')
data = file_obj.read([<count>]) #the type of data will be
string
data = file_obj.readlines() #the type of data will be list of
strings

Close the file: close()


Syntax:
file_obj.close()
Read/write content from/to the
file(r+,w+,a+)
 tell() - will give cursor position
 seek() - change the cursor position
seek(position,offset) where,offset=0(begining)/1(current
position)/2(end)

using with keyword:


We don't need to explicitly call the close() method. It is done
internally.
Syntax:
with open(<file_name>,<mode>) as file_obj:
CSV file handling
CSV (Comma Separated Values) is a simple file format used to store tabular
data, such as a spreadsheet or database.
CSV file is platform independent.
 Reading a CSV file
For working CSV files in python, there is an inbuilt module called csv.
1. CSV File Reader(using csv.reader) –non relevant data,content in the
form of list
2. CSV File Reader(using csv.DictReader)-relevant data,content in the
form of dictionary
3. CSV File Writer(using csv.writer)
4. CSV File Writer(using csv.DictWriter)
Any Questions??
THANK YOU

Vous aimerez peut-être aussi