SlideShare a Scribd company logo
1 of 26
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

What's hot

Sinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящееSinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящее.toster
 
CRaSH the shell for the Java Virtual Machine
CRaSH the shell for the Java Virtual MachineCRaSH the shell for the Java Virtual Machine
CRaSH the shell for the Java Virtual MachineGR8Conf
 
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski PROIDEA
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with phpElizabeth Smith
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basicsAbhay Sapru
 
HTTP HOST header attacks
HTTP HOST header attacksHTTP HOST header attacks
HTTP HOST header attacksDefconRussia
 
PHPerのためのPerl入門@ Kansai.pm#12
PHPerのためのPerl入門@ Kansai.pm#12PHPerのためのPerl入門@ Kansai.pm#12
PHPerのためのPerl入門@ Kansai.pm#12Kazuki KOMORI
 
Don’t block the event loop!
Don’t block the event loop!Don’t block the event loop!
Don’t block the event loop!hujinpu
 
Real Time Web Applications and Merb
Real Time Web Applications and MerbReal Time Web Applications and Merb
Real Time Web Applications and MerbCollin Miller
 
Ninja Git: Save Your Master
Ninja Git: Save Your MasterNinja Git: Save Your Master
Ninja Git: Save Your MasterNicola Paolucci
 
Loophole: Timing Attacks on Shared Event Loops in Chrome
Loophole: Timing Attacks on Shared Event Loops in ChromeLoophole: Timing Attacks on Shared Event Loops in Chrome
Loophole: Timing Attacks on Shared Event Loops in Chromecgvwzq
 

What's hot (17)

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

Viewers also liked

流程語法與函式
流程語法與函式流程語法與函式
流程語法與函式Justin Lin
 
資料永續與交換
資料永續與交換資料永續與交換
資料永續與交換Justin Lin
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
類別的繼承
類別的繼承類別的繼承
類別的繼承Justin Lin
 
除錯、測試與效能
除錯、測試與效能除錯、測試與效能
除錯、測試與效能Justin Lin
 
《Python 3.5 技術手冊》第二章草稿
《Python 3.5 技術手冊》第二章草稿《Python 3.5 技術手冊》第二章草稿
《Python 3.5 技術手冊》第二章草稿Justin Lin
 
並行與平行
並行與平行並行與平行
並行與平行Justin Lin
 
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
從 REPL 到 IDE
從 REPL 到 IDE從 REPL 到 IDE
從 REPL 到 IDEJustin Lin
 
open() 與 io 模組
open() 與 io 模組open() 與 io 模組
open() 與 io 模組Justin Lin
 
從模組到類別
從模組到類別從模組到類別
從模組到類別Justin Lin
 
PyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialPyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialJustin Lin
 
3D 之邏輯與美感交會 - OpenSCAD
3D 之邏輯與美感交會 - OpenSCAD3D 之邏輯與美感交會 - OpenSCAD
3D 之邏輯與美感交會 - OpenSCADJustin Lin
 
網站系統安全及資料保護設計認知
網站系統安全及資料保護設計認知網站系統安全及資料保護設計認知
網站系統安全及資料保護設計認知Justin Lin
 
常用內建模組
常用內建模組常用內建模組
常用內建模組Justin Lin
 
型態與運算子
型態與運算子型態與運算子
型態與運算子Justin Lin
 

Viewers also liked (20)

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

Similar to Python Programming Essentials - M22 - File Operations

Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsPuppet
 
Composer for busy developers - DPC13
Composer for busy developers - DPC13Composer for busy developers - DPC13
Composer for busy developers - DPC13Rafael Dohms
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStackBram Vogelaar
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentationbrian_dailey
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them Allegypt
 
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionDEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionFelipe Prado
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Rafael Dohms
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet
 
Drupal Camp Brighton 2015: Ansible Drupal Medicine show
Drupal Camp Brighton 2015: Ansible Drupal Medicine showDrupal Camp Brighton 2015: Ansible Drupal Medicine show
Drupal Camp Brighton 2015: Ansible Drupal Medicine showGeorge Boobyer
 
Best practices for crafting high quality PHP apps (php[world] 2019)
Best practices for crafting high quality PHP apps (php[world] 2019)Best practices for crafting high quality PHP apps (php[world] 2019)
Best practices for crafting high quality PHP apps (php[world] 2019)James Titcumb
 
Embed--Basic PERL XS
Embed--Basic PERL XSEmbed--Basic PERL XS
Embed--Basic PERL XSbyterock
 
Love Your Command Line
Love Your Command LineLove Your Command Line
Love Your Command LineLiz Henry
 
Greenfield Puppet: Getting it right from the start
Greenfield Puppet: Getting it right from the startGreenfield Puppet: Getting it right from the start
Greenfield Puppet: Getting it right from the startDavid Danzilio
 
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...Puppet
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - SummaryNugroho Gito
 

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

Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of Laptops
 
Composer for busy developers - DPC13
Composer for busy developers - DPC13Composer for busy developers - DPC13
Composer for busy developers - DPC13
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them All
 
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionDEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
 
Git::Hooks
Git::HooksGit::Hooks
Git::Hooks
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13Composer for Busy Developers - php|tek13
Composer for Busy Developers - php|tek13
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
Drupal Camp Brighton 2015: Ansible Drupal Medicine show
Drupal Camp Brighton 2015: Ansible Drupal Medicine showDrupal Camp Brighton 2015: Ansible Drupal Medicine show
Drupal Camp Brighton 2015: Ansible Drupal Medicine show
 
Best practices for crafting high quality PHP apps (php[world] 2019)
Best practices for crafting high quality PHP apps (php[world] 2019)Best practices for crafting high quality PHP apps (php[world] 2019)
Best practices for crafting high quality PHP apps (php[world] 2019)
 
Embed--Basic PERL XS
Embed--Basic PERL XSEmbed--Basic PERL XS
Embed--Basic PERL XS
 
Love Your Command Line
Love Your Command LineLove Your Command Line
Love Your Command Line
 
Greenfield Puppet: Getting it right from the start
Greenfield Puppet: Getting it right from the startGreenfield Puppet: Getting it right from the start
Greenfield Puppet: Getting it right from the start
 
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...
Puppet Camp Boston 2014: Greenfield Puppet: Getting it right from the start (...
 
Shell Script
Shell ScriptShell Script
Shell Script
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - Summary
 

More from P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 

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

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

Python Programming Essentials - M22 - File Operations

  • 1. 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
  • 2. © 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
  • 3. © SkillBrew http://skillbrew.com Open a file 3 f = open('alice.txt', 'r') print f.read() f.close()
  • 4. © 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
  • 5. © 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
  • 6. © 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
  • 7. © 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
  • 8. © 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
  • 9. © SkillBrew http://skillbrew.com Methods of File Objects  read()  readline()  readlines()  write()  seek()  tell() 9
  • 10. © 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
  • 11. © 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
  • 12. © 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,
  • 13. © 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
  • 14. © 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
  • 15. © 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.)']
  • 16. © 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()
  • 17. © 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
  • 18. © SkillBrew http://skillbrew.com write() (2) 18 Output: wonderland.txt The White Rabbit appears again in search of the Duchess's gloves and fan
  • 19. © 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
  • 20. © 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.)
  • 21. © 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
  • 22. © 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
  • 23. © 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
  • 24. © 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
  • 25. © SkillBrew http://skillbrew.com Summary  Open a file  Methods of file objects (read, readline, readlines, write, seek, tell) 25
  • 26. © 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