SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 

Mais procurados (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
 

Semelhante a Python - Lecture 8

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
 

Semelhante a 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
 

Mais de 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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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