SlideShare a Scribd company logo
Python
Lecture 8Lecture 8
- Ravi Kiran Khareedi
Files
• Opening a file
• Python has a built-in open() function, which
takes a filename as an argument.
• Filename argument can just denote a file• Filename argument can just denote a file
name or the path of the file.
• The path can be absolute or relative.
• In python, / is used to specify the path
• Ex: afile = open(‘test.txt’)
Absolute vs Relative Path
• Absolute Path:
– Always starts from the root path, in windows from the
drive letter.
• Relative Path:• Relative Path:
– It’s the path with respect to the current dirctory.
TASK:
Try to specify the file path in windows style (using )
Stream Objects
• The open() function returns a stream object,
which has methods and attributes for getting
information about and manipulating a stream
of characters.of characters.
afile = open(‘test.txt’)
print afile.name
print afile.mode
• mode is ‘r’ by default
Files
• Reading a file
• File is read by calling a read() method of the stream
object
• The result is a string
• TASK
df = open(‘test.txt')
print df.read()
print "Read Again"
print df.read()
Files - Reading
• Reading a file twice don’t give any exception but
simply returns a empty string.
• So how to re-read a file? Let’s see:
– afile.read()
afile.seek(0)
afile.read()afile.read()
• seek() method moves the control to a specific byte position
• read() method takes optional parameters to read the specific
number of characters
• tell() method of the stream object is used to know thw
current position of the pointer(in simple words, the
cursor)
Files Reading
• seek(offset[, from])
• The offset argument indicates the number of bytes to be moved.
• The from argument specifies the reference position from where the bytes
are to be moved.
– If from is set to 0, it means use the beginning of the file as the reference– If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position and if
it is set to 2 then the end of the file would be taken as the reference position.
Files
• Note:
• The seek() and tell() methods always count bytes, but since you
opened this file as text, the read() method counts characters
• (In case of English characters, both are same)
• TASK
df = open(‘test.txt')
print df.read()
Now try to move the file to some other folder. Lets see what happens
Files - Close
• Closing a File
• Open file consume some resources, depending on the file
mode, Its important to close the file once its used.
• afile.close()
• Attribute closed will return if a file is closed or not.• Attribute closed will return if a file is closed or not.
• afile.closed return true or false.
• close() just closes a file but not destroy the afile object.
File - Close
• You can’t read from a closed file; that raises an IOError
exception.
• You can’t seek in a closed file either.
• There’s no current position in a closed file, so the tell()
method also fails.method also fails.
• Perhaps surprisingly, calling the close() method on a
stream object whose file has been closed does not
• raise an exception. It’s just a no-op.
• Closed stream objects do have one useful attribute: the
closed attribute will confirm that the file is closed.
File – Automatic Close
• To make sure the file is closed even if the program is crashed by using
try(), finally block.
• (Lets see what is it in later stages)
• But python 2.6 has a better solution:
with open('examples/chinese.txt', encoding='utf-8') as a_file:
a_file.seek(17)
a_character = a_file.read(1)a_character = a_file.read(1)
print(a_character)
• This code calls open(), but it never calls a file.close(). The with
statement starts a code block, like an if statement or a for loop.
• Inside this code block, you can use the variable a file as the stream
object returned from the call to open(). All the regular stream object
methods are available — seek(), read() etc
• When the with block ends, Python calls a_file.close() automatically.
Reading a Line at a time
• for a_line in a_file:
• Reads one line from a_file
• TASK – GENERAL
Write a program to generate first 10 numbers of the fibonacci• Write a program to generate first 10 numbers of the fibonacci
series
• Ex: 0,1,1,2,3,5 …..
File - Writing
• For writing to a file, open the file in write mode.
• There are 2 modes for writing:
– Write mode - mode = ‘w’ as parameter in open()
• Overwrite the data from the beginning of the file (Previous content is lost)
– Append mode - mode = ‘a’ as parameter in open()
• Adds data to the end of the file
Both creates a file automatically if it doesn’t existBoth creates a file automatically if it doesn’t exist
Ex: 1. df = open(‘test.txt’, mode = ‘w’)
df.write(‘python’)
df.close()
2. df = open(‘test.txt’, mode = ‘w’)
df.write(‘python’)
df.close()
By default, the mode is ‘r’ (read) hence its not specific while reading.
Binary Files
• Few files has to be opened in binary mode.
• Ex: Image Files
• an_image = open('examples/beauregard.jpg', mode='rb’)
• We just need to mention the mode as b along with w or r to• We just need to mention the mode as b along with w or r to
specify it’s a binary file.
Renaming Files
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
• The rename() Method:• The rename() Method:
• os.rename(current_file_name, new_file_name)
• Ex:
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
Deleting Files
• The remove() Method:
• os.remove(file_name)
• Syntax:
import osimport os
# Delete file test2.txt
os.remove("text2.txt")
Python Directories
• Python can handle directory option using the
os module
• mkdir()
• Creates directories in the current directory.• Creates directories in the current directory.
• Syntax:
• os.mkdir("newdir")
Python directories
• The getcwd() Method:
• getcwd()
• The getcwd() method displays the current working
directory.
• os.getcwd()
• The rmdir() Method:
• os.rmdir('dirname')
• The rmdir() method deletes the directory, which is passed
as an argument in the method.
• Before removing a directory, all the contents in it should be
removed.
TASK - GENERAL
• Write a program to check if a given string is
palidrome
• Ex: MADAM is a palindrome
References
• Dive into Python
• http://www.tutorialspoint.com/python/pytho
n_files_io.htm

More Related Content

What's hot

Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
Felix Z. Hoffmann
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
keeeerty
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
Python-File handling-slides-pkt
Python-File handling-slides-pktPython-File handling-slides-pkt
Python-File handling-slides-pkt
Pradyumna Tripathy
 
python file handling
python file handlingpython file handling
python file handling
jhona2z
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 

What's hot (19)

Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Python-files
Python-filesPython-files
Python-files
 
Python file handling
Python file handlingPython file handling
Python file handling
 
Python-File handling-slides-pkt
Python-File handling-slides-pktPython-File handling-slides-pkt
Python-File handling-slides-pkt
 
python file handling
python file handlingpython file handling
python file handling
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
File handling
File handlingFile handling
File handling
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 

Similar to Python - Lecture 8

CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
botin17097
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
ShaswatSurya
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
qover
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
RohitKurdiya1
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
files.pptx
files.pptxfiles.pptx
files.pptx
KeerthanaM738437
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
Vishal Dutt
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
Karudaiyar Ganapathy
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
VrushaliSolanke
 
File handing in C
File handing in CFile handing in C
File handing in C
shrishcg
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
YashAgarwal413109
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 

Similar to Python - Lecture 8 (20)

CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
File handing in C
File handing in CFile handing in C
File handing in C
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 

More from Ravi Kiran Khareedi

Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
Ravi Kiran Khareedi
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
Ravi Kiran Khareedi
 
Python - Lecture 10
Python - Lecture 10Python - Lecture 10
Python - Lecture 10
Ravi Kiran Khareedi
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
Ravi Kiran Khareedi
 
Python - Lecture 7
Python - Lecture 7Python - Lecture 7
Python - Lecture 7
Ravi Kiran Khareedi
 
Python - Lecture 6
Python - Lecture 6Python - Lecture 6
Python - Lecture 6
Ravi Kiran Khareedi
 
Python - Lecture 5
Python - Lecture 5Python - Lecture 5
Python - Lecture 5
Ravi Kiran Khareedi
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
Ravi Kiran Khareedi
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
Ravi Kiran Khareedi
 
Python - Lecture 2
Python - Lecture 2Python - Lecture 2
Python - Lecture 2
Ravi Kiran Khareedi
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
Ravi Kiran Khareedi
 

More from Ravi Kiran Khareedi (11)

Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Python - Lecture 10
Python - Lecture 10Python - Lecture 10
Python - Lecture 10
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
 
Python - Lecture 7
Python - Lecture 7Python - Lecture 7
Python - Lecture 7
 
Python - Lecture 6
Python - Lecture 6Python - Lecture 6
Python - Lecture 6
 
Python - Lecture 5
Python - Lecture 5Python - Lecture 5
Python - Lecture 5
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Python - Lecture 2
Python - Lecture 2Python - Lecture 2
Python - Lecture 2
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 

Python - Lecture 8

  • 1. Python Lecture 8Lecture 8 - Ravi Kiran Khareedi
  • 2. Files • Opening a file • Python has a built-in open() function, which takes a filename as an argument. • Filename argument can just denote a file• Filename argument can just denote a file name or the path of the file. • The path can be absolute or relative. • In python, / is used to specify the path • Ex: afile = open(‘test.txt’)
  • 3. Absolute vs Relative Path • Absolute Path: – Always starts from the root path, in windows from the drive letter. • Relative Path:• Relative Path: – It’s the path with respect to the current dirctory. TASK: Try to specify the file path in windows style (using )
  • 4. Stream Objects • The open() function returns a stream object, which has methods and attributes for getting information about and manipulating a stream of characters.of characters. afile = open(‘test.txt’) print afile.name print afile.mode • mode is ‘r’ by default
  • 5. Files • Reading a file • File is read by calling a read() method of the stream object • The result is a string • TASK df = open(‘test.txt') print df.read() print "Read Again" print df.read()
  • 6. Files - Reading • Reading a file twice don’t give any exception but simply returns a empty string. • So how to re-read a file? Let’s see: – afile.read() afile.seek(0) afile.read()afile.read() • seek() method moves the control to a specific byte position • read() method takes optional parameters to read the specific number of characters • tell() method of the stream object is used to know thw current position of the pointer(in simple words, the cursor)
  • 7. Files Reading • seek(offset[, from]) • The offset argument indicates the number of bytes to be moved. • The from argument specifies the reference position from where the bytes are to be moved. – If from is set to 0, it means use the beginning of the file as the reference– If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
  • 8. Files • Note: • The seek() and tell() methods always count bytes, but since you opened this file as text, the read() method counts characters • (In case of English characters, both are same) • TASK df = open(‘test.txt') print df.read() Now try to move the file to some other folder. Lets see what happens
  • 9. Files - Close • Closing a File • Open file consume some resources, depending on the file mode, Its important to close the file once its used. • afile.close() • Attribute closed will return if a file is closed or not.• Attribute closed will return if a file is closed or not. • afile.closed return true or false. • close() just closes a file but not destroy the afile object.
  • 10. File - Close • You can’t read from a closed file; that raises an IOError exception. • You can’t seek in a closed file either. • There’s no current position in a closed file, so the tell() method also fails.method also fails. • Perhaps surprisingly, calling the close() method on a stream object whose file has been closed does not • raise an exception. It’s just a no-op. • Closed stream objects do have one useful attribute: the closed attribute will confirm that the file is closed.
  • 11. File – Automatic Close • To make sure the file is closed even if the program is crashed by using try(), finally block. • (Lets see what is it in later stages) • But python 2.6 has a better solution: with open('examples/chinese.txt', encoding='utf-8') as a_file: a_file.seek(17) a_character = a_file.read(1)a_character = a_file.read(1) print(a_character) • This code calls open(), but it never calls a file.close(). The with statement starts a code block, like an if statement or a for loop. • Inside this code block, you can use the variable a file as the stream object returned from the call to open(). All the regular stream object methods are available — seek(), read() etc • When the with block ends, Python calls a_file.close() automatically.
  • 12. Reading a Line at a time • for a_line in a_file: • Reads one line from a_file • TASK – GENERAL Write a program to generate first 10 numbers of the fibonacci• Write a program to generate first 10 numbers of the fibonacci series • Ex: 0,1,1,2,3,5 …..
  • 13. File - Writing • For writing to a file, open the file in write mode. • There are 2 modes for writing: – Write mode - mode = ‘w’ as parameter in open() • Overwrite the data from the beginning of the file (Previous content is lost) – Append mode - mode = ‘a’ as parameter in open() • Adds data to the end of the file Both creates a file automatically if it doesn’t existBoth creates a file automatically if it doesn’t exist Ex: 1. df = open(‘test.txt’, mode = ‘w’) df.write(‘python’) df.close() 2. df = open(‘test.txt’, mode = ‘w’) df.write(‘python’) df.close() By default, the mode is ‘r’ (read) hence its not specific while reading.
  • 14. Binary Files • Few files has to be opened in binary mode. • Ex: Image Files • an_image = open('examples/beauregard.jpg', mode='rb’) • We just need to mention the mode as b along with w or r to• We just need to mention the mode as b along with w or r to specify it’s a binary file.
  • 15. Renaming Files • Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files. • The rename() Method:• The rename() Method: • os.rename(current_file_name, new_file_name) • Ex: import os # Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" )
  • 16. Deleting Files • The remove() Method: • os.remove(file_name) • Syntax: import osimport os # Delete file test2.txt os.remove("text2.txt")
  • 17. Python Directories • Python can handle directory option using the os module • mkdir() • Creates directories in the current directory.• Creates directories in the current directory. • Syntax: • os.mkdir("newdir")
  • 18. Python directories • The getcwd() Method: • getcwd() • The getcwd() method displays the current working directory. • os.getcwd() • The rmdir() Method: • os.rmdir('dirname') • The rmdir() method deletes the directory, which is passed as an argument in the method. • Before removing a directory, all the contents in it should be removed.
  • 19. TASK - GENERAL • Write a program to check if a given string is palidrome • Ex: MADAM is a palindrome
  • 20. References • Dive into Python • http://www.tutorialspoint.com/python/pytho n_files_io.htm