SlideShare a Scribd company logo
http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
File operations in python
Pavan Verma
@YinYangPavan
1
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
© SkillBrew http://skillbrew.com
Note
 Please download file alice.txt from
https://dl.dropboxusercontent.com/u/40996392/Hap
piestMinds/alice.txt for examples in this module
2
© SkillBrew http://skillbrew.com
Open a file
3
f = open('alice.txt', 'r')
print f.read()
f.close()
© SkillBrew http://skillbrew.com
Open a File (2)
Output:
Well!' thought Alice to herself, 'after such a fall as this,
I shall think nothing of tumbling down stairs!
How brave they'll all think me at home!
Why, I wouldn't say anything about it,
even if I fell off the top of the house!'
(Which was very likely true.)
4
© SkillBrew http://skillbrew.com
Open a file (3)
5
• open function call takes in two parameters filename,
mode
• filename can be a absolute path or a relative path
• On linux:
open('/home/xyz/workspace/alice.txt',
'r')
• On windows:
open('C:Usersxyzworkspacealice.txt',
'r')
• If just filename is added python will look for file in
current directory where the program is being executed
© SkillBrew http://skillbrew.com
Open a file (4)
6
f = open('alice.txt', 'r')
• mode is the mode in which you want to open the file
There are mainly three modes
1. Read
2. Write
3. Append
• By default the mode is Read
© SkillBrew http://skillbrew.com
Mode Details
r
File will only be read. The file pointer is placed at the
beginning of the file. This is the default mode.
w
Opens a file for writing only. Overwrites the file if the
file exists. If the file does not exist, creates a new file
for writing..
a
Opens a file for appending. The file pointer is at the
end of the file if the file exists. If the file does not exist,
it creates a new file for writing.
File modes
7
© SkillBrew http://skillbrew.com
Mode Details
r+
Opens a file for both reading and writing. The file
pointer will be at the beginning of the file
w+
Opens a file for both writing and reading. Overwrites
the existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
a+
Opens a file for both appending and reading. The file
pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
File modes (2)
8
© SkillBrew http://skillbrew.com
Methods of File Objects
 read()
 readline()
 readlines()
 write()
 seek()
 tell()
9
© SkillBrew http://skillbrew.com
read()
10
f = open('alice.txt', 'r')
print f.read()
f.close()
read(size)
• size is an optional argument, If size is omitted or
negative entire file contents are read at once
• If end of file has been reached f.read()returns empty
string
© SkillBrew http://skillbrew.com
read() (2)
11
f = open('alice.txt', 'r')
print f.read(100)
f.close()
Output:
Well!' thought Alice to herself, 'after such a fall as this,
I shall think nothing of tumbling down
© SkillBrew http://skillbrew.com
readline()
12
f = open('alice.txt', 'r')
print f.readline()
f.close()
Output:
Well!' thought Alice to herself, 'after such a fall as this,
© SkillBrew http://skillbrew.com
readline() (2)
13
f = open('alice.txt', 'r')
print f.readline()
f.close()
• Reads a single line from the file
• If f.readline() returns an empty string, the end of
the file has been reached
© SkillBrew http://skillbrew.com
readlines()
14
f = open('alice.txt', 'r')
lines = f.readlines()
print lines
f.close()
readlines() reads the entire file and returns a
list of lines
© SkillBrew http://skillbrew.com
readlines() (2)
15
Output:
["Well!' thought Alice to herself, 'after such a fall as this,n",
'I shall think nothing of tumbling down stairs!n',
"How brave they'll all think me at home!n",
"Why, I wouldn't say anything about it,n",
"even if I fell off the top of the house!'n",
'(Which was very likely true.)']
© SkillBrew http://skillbrew.com
readlines() (2)
16
f = open('alice.txt', 'r')
lines = f.readlines()
print lines
for line in lines:
print line
f.close()
© SkillBrew http://skillbrew.com
write()
17
text = "The White Rabbit appears again
in search of the Duchess's gloves and fan"
f = open('wonderland.txt', 'w')
f.write(text)
f.close()
write(str) writes a string of characters to a
file
• wonderland.txt is created if it did not
exist
• If wonderland.txt existed then it would
be overwritten by this text
© SkillBrew http://skillbrew.com
write() (2)
18
Output:
wonderland.txt
The White Rabbit appears again in search of
the Duchess's gloves and fan
© SkillBrew http://skillbrew.com
write() (3)
19
f1 = open('alice.txt', 'r')
text = f1.read()
f2 = open('wonderland.txt', 'w')
f2.write(text)
f2.close()
f1.close()
Reads text from alice.txt and writes to
wonderland.txt
© SkillBrew http://skillbrew.com
write()
20
Ouput: wonderland.txt
Well!' thought Alice to herself, 'after such a fall as this,
I shall think nothing of tumbling down stairs!
How brave they'll all think me at home!
Why, I wouldn't say anything about it,
even if I fell off the top of the house!'
(Which was very likely true.)
© SkillBrew http://skillbrew.com
append
21
text = "The White Rabbit appears again
in search of the Duchess's gloves and fan"
f = open('wonderland.txt', 'a')
f.write(text)
f.close()
Opening the file in append mode will move the file
pointer to end of the file
© SkillBrew http://skillbrew.com
append (2)
22
Ouput: wonderland.txt
Well!' thought Alice to herself, 'after such a fall as this,
I shall think nothing of tumbling down stairs!
How brave they'll all think me at home!
Why, I wouldn't say anything about it,
even if I fell off the top of the house!'
(Which was very likely true.)The White Rabbit appears again in search
of the Duchess's gloves and fan
© SkillBrew http://skillbrew.com
seek
23
f = open('wonderland.txt')
f.seek(7)
print f.readline()
f.close()
Output:
thought Alice to herself, 'after such a fall as this,
seek(offset) changes the file object position to offset
The offset by default is measured form beginning of file
© SkillBrew http://skillbrew.com
tell
24
f = open('alice.txt', 'r')
f.seek(7) # changes file pos to offset 7
print f.readline()
print f.tell() # tells the current pos
Output:
thought Alice to herself, 'after such a fall as this,
I shall
62
tell() returns an integer giving the file object’s current position
© SkillBrew http://skillbrew.com
Summary
 Open a file
 Methods of file objects (read, readline, readlines,
write, seek, tell)
25
© SkillBrew http://skillbrew.com
Resources
 reading and writing files
http://docs.python.org/2/tutorial/inputoutput.html#reading-
and-writing-files
 Methods on file objects
http://docs.python.org/2/tutorial/inputoutput.html#methods-
of-file-objects
26

More Related Content

PDF
Battle of the Stacks
PDF
Docker @ Data Science Meetup
PDF
Docker for data science
PDF
rioinfo2012
PDF
Stop js-1999
PDF
Discovering Volume Plugins with Applications using Docker Toolbox and VirtualBox
PDF
Productivity tips for developers
PPT
Rush, a shell that will yield to you
Battle of the Stacks
Docker @ Data Science Meetup
Docker for data science
rioinfo2012
Stop js-1999
Discovering Volume Plugins with Applications using Docker Toolbox and VirtualBox
Productivity tips for developers
Rush, a shell that will yield to you

What's hot (17)

PDF
Sinatra: прошлое, будущее и настоящее
PPTX
Unix shell scripting
PDF
CRaSH the shell for the Java Virtual Machine
PDF
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
PPTX
Socket programming with php
PDF
Ssh cookbook
PPT
01 linux basics
PPTX
Who Broke My Crypto
PPT
Unix shell scripting basics
PPTX
HTTP HOST header attacks
ODP
WebSockets with PHP: Mission impossible
KEY
PHPerのためのPerl入門@ Kansai.pm#12
KEY
Don’t block the event loop!
PPT
Real Time Web Applications and Merb
PDF
Ninja Git: Save Your Master
PDF
Loophole: Timing Attacks on Shared Event Loops in Chrome
PDF
Sinatra: прошлое, будущее и настоящее
Unix shell scripting
CRaSH the shell for the Java Virtual Machine
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
Socket programming with php
Ssh cookbook
01 linux basics
Who Broke My Crypto
Unix shell scripting basics
HTTP HOST header attacks
WebSockets with PHP: Mission impossible
PHPerのためのPerl入門@ Kansai.pm#12
Don’t block the event loop!
Real Time Web Applications and Merb
Ninja Git: Save Your Master
Loophole: Timing Attacks on Shared Event Loops in Chrome
Ad

Viewers also liked (20)

PDF
流程語法與函式
PPTX
Python
PDF
資料永續與交換
PPTX
Python 3 Programming Language
PDF
類別的繼承
PDF
除錯、測試與效能
PDF
《Python 3.5 技術手冊》第二章草稿
PDF
並行與平行
PPTX
Python Programming Essentials - M44 - Overview of Web Development
PDF
從 REPL 到 IDE
PDF
例外處理
PDF
open() 與 io 模組
PDF
資料結構
PDF
從模組到類別
PDF
PyCon Taiwan 2013 Tutorial
PDF
3D 之邏輯與美感交會 - OpenSCAD
PDF
網站系統安全及資料保護設計認知
PDF
進階主題
PDF
常用內建模組
PDF
型態與運算子
流程語法與函式
Python
資料永續與交換
Python 3 Programming Language
類別的繼承
除錯、測試與效能
《Python 3.5 技術手冊》第二章草稿
並行與平行
Python Programming Essentials - M44 - Overview of Web Development
從 REPL 到 IDE
例外處理
open() 與 io 模組
資料結構
從模組到類別
PyCon Taiwan 2013 Tutorial
3D 之邏輯與美感交會 - OpenSCAD
網站系統安全及資料保護設計認知
進階主題
常用內建模組
型態與運算子
Ad

Similar to Python Programming Essentials - M22 - File Operations (20)

PPT
Python File functions
PPTX
What is FIle and explanation of text files.pptx
PDF
FileHandling2023_Text File.pdf CBSE 2014
PPTX
pspp-rsk.pptx
PDF
PPTX
Unit V.pptx
PDF
File and directories in python
PPTX
this is about file concepts in class 12 in python , text file, binary file, c...
PDF
Python 3.x File Object Manipulation Cheatsheet
PPTX
File Operations in python Read ,Write,binary file etc.
PDF
file handling.pdf
PPTX
Datafile Handeling Presentation by UNKNOWN pptx
PPTX
DATA FILEEE BY UNKououououoNOWN PART @ IDK
PPT
Python file handlings
DOCX
File Handling in python.docx
PPTX
pp5-filehandling- python 200824063109 (1).pptx
PDF
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
PPTX
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
PDF
23CS101T PSPP python program - UNIT 5.pdf
PPTX
files.pptx
Python File functions
What is FIle and explanation of text files.pptx
FileHandling2023_Text File.pdf CBSE 2014
pspp-rsk.pptx
Unit V.pptx
File and directories in python
this is about file concepts in class 12 in python , text file, binary file, c...
Python 3.x File Object Manipulation Cheatsheet
File Operations in python Read ,Write,binary file etc.
file handling.pdf
Datafile Handeling Presentation by UNKNOWN pptx
DATA FILEEE BY UNKououououoNOWN PART @ IDK
Python file handlings
File Handling in python.docx
pp5-filehandling- python 200824063109 (1).pptx
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
23CS101T PSPP python program - UNIT 5.pdf
files.pptx

More from P3 InfoTech Solutions Pvt. Ltd. (20)

PPTX
Python Programming Essentials - M40 - Invoking External Programs
PPTX
Python Programming Essentials - M39 - Unit Testing
PPTX
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PPTX
Python Programming Essentials - M34 - List Comprehensions
PPTX
Python Programming Essentials - M31 - PEP 8
PPTX
Python Programming Essentials - M29 - Python Interpreter and Files
PPTX
Python Programming Essentials - M28 - Debugging with pdb
PPTX
Python Programming Essentials - M27 - Logging module
PPTX
Python Programming Essentials - M25 - os and sys modules
PPTX
Python Programming Essentials - M24 - math module
PPTX
Python Programming Essentials - M23 - datetime module
PPTX
Python Programming Essentials - M21 - Exception Handling
PPTX
Python Programming Essentials - M20 - Classes and Objects
PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
PPTX
Python Programming Essentials - M18 - Modules and Packages
PPTX
Python Programming Essentials - M17 - Functions
PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
PPTX
Python Programming Essentials - M15 - References
PPTX
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M24 - math module
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M15 - References
Python Programming Essentials - M14 - Dictionaries

Python Programming Essentials - M22 - File Operations