SlideShare una empresa de Scribd logo
1 de 25
Topic: Files Operations
GE 8151 Problem Solving and Python
Programming
Presented by, Dr.G.Rajiv Suresh Kumar,
HoD/CSE,JCTCET
FILES
Files
A File is collection of data stored on a secondary storage
device like hard disk. Data on non-volatile storage
media is stored in named locations on the media called
files. File is a named location on disk to store related
information.
While a program is running, its data is in memory. When
the program ends, or the computer shuts down, data in
memory disappears. To store data permanently, you
have to put it in a file. Files are usually stored on a hard
drive, floppy drive, or CD-ROM.
File continuation
• When there are a large number of files, they are
often organized into directories (also called
"folders"). Each file is identified by a unique
name, or a combination of a file name and a
directory name.
• Hence, in Python, a file operation takes place in
the following order.
Open a file
Read or write (perform operation)
Close the file
File Types
• Text files
• Binary files
Text files
• A text file is a file that contains printable
characters and whitespace, organized into
lines separated by newline characters. Text
files are structured as a sequence of lines,
where each line includes a sequence of
characters. Since Python is specifically
designed to process text files, it provides
methods that make the job easy.
Binary files
• A binary file is any type of file that is not a text
file. Because of their nature, binary files can
only be processed by an application that know
or understand the file’s structure. In other
words, they must be applications that can read
and interpret binary.
File operation
Open a file
Read or write (perform operation)
Close the file
Attributes of a file
Attribute Description
file.closed If file is closed return true else false
file.mode Returns one of the modes in which the current file is opened
file.name Returns the name of the file
Example for attributes
• fileread= open( “text.txt” , ”r+” )
• print (“Name of the file : ”,fileread.name)
• print (“Closed or not : ”,fileread.closed)
print(“opening mode : ”,fileread.mode)
OUTPUT:
• Name of the file : text.txt
• Closed or not : False
• opening mode : r+
Opening a file
• Python has a built-in function open() to open a file.
This function returns a file object, also called a handle,
as it is used to read or modify the file accordingly.
Syntax:
• Fileobject = open(“filename or file path” ,”access
mode”)
• >>> f = open("test.txt") # open file in current directory
by directly specifying the name of the file.
• >>> f = open("C:/Python33/README.txt") # specifying
full path.
• >>> f = open(“test.txt” , “r”) # open the file by
mentioning file name and mode
File opening Modes
Mode Description
r Opens a file for reading only. 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 placed at the end of the file. If
the file does not exist, creates a new file for writing
r+ Opens a file for both reading and writing. The file pointer is placed at the
beginning of the file.
W+ Opens a file for both reading and writing. Overwrites the 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 reading and appending. The file pointer is placed at the
end of the file. If the file does not exist, creates a new file for reading and
writing.
File opening Modes
Mode Description
rb Opens a file for both reading in binary format. The file pointer is placed at the
beginning of the file
wb Opens a file for writing only in binary format.Overwrites the file if the file
exists.If the file does not exist, creates a new file for writing
ab Opens a file for appending in binary format. The file pointer is placed at the end
of the file. If the file does not exist, creates a new file for writing
FILE CLOSING
• When the operations that are to be performed o
n a opened file are finished, we have to close the
file in order to release the resources. The closing
is done with a built-in function close()
Syntax:
fileobject.close()
Example:
f= open(“text.txt” , “w”) #open a file
#perform some operations
f.close() #close the file
Writing to a file
• After opening a file, we have to perform some operations on the
file. In order to write into a file, we have to open it with w mode, or
a mode, or any other writing – enabling mode. write() method
enables us to write any string to a opened file.
Syntax:
Fileobject=open(“file.txt”,”w”)
Fileobject.write(“String to be written”)
Example:
fo = open("foo.txt", "w")
fo.write( "Python is a great language.nYeah its great!!n");
print(“success”)
fo.close()
Reading a file
The text files can be read in four different ways listed below:
Using read Method
Using readlines Method
Using readline Method
Syntax:
read()
<file variable name>.read()
When size is not specified entire file is read and the contents are
placed in the left hand side variable.
<file variable name>.read(<size>)
When size is specified , the size number of characters are read.
When an empty file is read no error is displayed but an empty string
is returned.
readlines()
<file variable name>.readlines(<size>) #size optional
When size is not specified entire file is read and
each line is added in a list. When size is specified
, the lines that make up the size bytes are
read.When an empty file is read no error is
displayed but an empty list is returned.
Example for all types of reading a file: Assume
the content of a file:
Hello Good morning
We are learning python
Its very interesting
Program
fileread = open(“text.txt”, “r”)
Str=fileread.read(10)
Length=len(Str)
print (str)
print (Length)
Str=fileread.read(20)
print (str)
Str= fileread.read()
print (str)
Str=fileread.readlines()
print(Str) fileread.close()
Output:
Hello Good
10
morning
We are learn
ing python
Its very interesting
Hello Good morning
We are learning python
Its very interesting
Renaming a file
An existing file can be renamed by using the
method rename()
Syntax:
os.rename(current filename, new filename)
Example:
>>> import os
>>>os.rename(“C:/Python27/myfile.txt”,
“C:/Python27/myfile1.txt”)
Deleting a File
An existing file can be deleted by using the
method remove().
Syntax:
os.remove(filename)
Example:
>>> import os
>>>os.remove(“C:/Python27/myfile1.txt”)
Format Operator
• Definition:
The format operator is used to print the output
in a desired format. The % operator is the
format operator. It is also called as
interpolation operator. The % operator is also
used for modulus. The usage varies according
to the operands of the operator.
General syntax:
<format expression>%(values)
# The values is a tuple with exactly the number
of items specified by the format expression.
PROGRAM
print(“%d” %(45))
print(“%f”%(3.14159265358979))
print(“%0.2f”%(3.141592653589))
print (“Decimal : %u”%(24))
Print (“Octal : %o”%(24)) Print (“Hexadecimal :
%x”%(1254))
Print (“Hexadecimal : %X”%(1254))
X=40
print(“The given integer is %d”%X)
OUTPUT
45
3.141592
3.14
Decimal : 24
Octal : 30
Hexadecimal : 4e6
Hexadecimal : 4E6

Más contenido relacionado

Similar a pspp-rsk.pptx

File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.ssuser00ad4e
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15Vishal Dutt
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptxAmitKaur17
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptxqover
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdfsulekha24
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16Vishal Dutt
 

Similar a pspp-rsk.pptx (20)

File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
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
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 

Más de ARYAN552812

Presentation Quotes - Template by SlideLizard.en.pptx
Presentation Quotes - Template by SlideLizard.en.pptxPresentation Quotes - Template by SlideLizard.en.pptx
Presentation Quotes - Template by SlideLizard.en.pptxARYAN552812
 
CategoryABiologicalEffort.pptx
CategoryABiologicalEffort.pptxCategoryABiologicalEffort.pptx
CategoryABiologicalEffort.pptxARYAN552812
 
SMS based Poll Day Monitoring.ppt
SMS based Poll Day Monitoring.pptSMS based Poll Day Monitoring.ppt
SMS based Poll Day Monitoring.pptARYAN552812
 
PollDayArrangements.ppt
PollDayArrangements.pptPollDayArrangements.ppt
PollDayArrangements.pptARYAN552812
 
Full Wave Rectifier (P).docx
Full Wave Rectifier (P).docxFull Wave Rectifier (P).docx
Full Wave Rectifier (P).docxARYAN552812
 
See-Something-Phishy.pptx
See-Something-Phishy.pptxSee-Something-Phishy.pptx
See-Something-Phishy.pptxARYAN552812
 
Move files to OneDrive.pptx
Move files to OneDrive.pptxMove files to OneDrive.pptx
Move files to OneDrive.pptxARYAN552812
 
1.5 File Management Presentation.pptx
1.5 File Management Presentation.pptx1.5 File Management Presentation.pptx
1.5 File Management Presentation.pptxARYAN552812
 

Más de ARYAN552812 (9)

Presentation Quotes - Template by SlideLizard.en.pptx
Presentation Quotes - Template by SlideLizard.en.pptxPresentation Quotes - Template by SlideLizard.en.pptx
Presentation Quotes - Template by SlideLizard.en.pptx
 
CategoryABiologicalEffort.pptx
CategoryABiologicalEffort.pptxCategoryABiologicalEffort.pptx
CategoryABiologicalEffort.pptx
 
SMS based Poll Day Monitoring.ppt
SMS based Poll Day Monitoring.pptSMS based Poll Day Monitoring.ppt
SMS based Poll Day Monitoring.ppt
 
PollDayArrangements.ppt
PollDayArrangements.pptPollDayArrangements.ppt
PollDayArrangements.ppt
 
lessonpp.ppt
lessonpp.pptlessonpp.ppt
lessonpp.ppt
 
Full Wave Rectifier (P).docx
Full Wave Rectifier (P).docxFull Wave Rectifier (P).docx
Full Wave Rectifier (P).docx
 
See-Something-Phishy.pptx
See-Something-Phishy.pptxSee-Something-Phishy.pptx
See-Something-Phishy.pptx
 
Move files to OneDrive.pptx
Move files to OneDrive.pptxMove files to OneDrive.pptx
Move files to OneDrive.pptx
 
1.5 File Management Presentation.pptx
1.5 File Management Presentation.pptx1.5 File Management Presentation.pptx
1.5 File Management Presentation.pptx
 

Último

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 

Último (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 

pspp-rsk.pptx

  • 1. Topic: Files Operations GE 8151 Problem Solving and Python Programming Presented by, Dr.G.Rajiv Suresh Kumar, HoD/CSE,JCTCET
  • 2. FILES Files A File is collection of data stored on a secondary storage device like hard disk. Data on non-volatile storage media is stored in named locations on the media called files. File is a named location on disk to store related information. While a program is running, its data is in memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a hard drive, floppy drive, or CD-ROM.
  • 3. File continuation • When there are a large number of files, they are often organized into directories (also called "folders"). Each file is identified by a unique name, or a combination of a file name and a directory name. • Hence, in Python, a file operation takes place in the following order. Open a file Read or write (perform operation) Close the file
  • 4. File Types • Text files • Binary files
  • 5. Text files • A text file is a file that contains printable characters and whitespace, organized into lines separated by newline characters. Text files are structured as a sequence of lines, where each line includes a sequence of characters. Since Python is specifically designed to process text files, it provides methods that make the job easy.
  • 6. Binary files • A binary file is any type of file that is not a text file. Because of their nature, binary files can only be processed by an application that know or understand the file’s structure. In other words, they must be applications that can read and interpret binary.
  • 7. File operation Open a file Read or write (perform operation) Close the file
  • 8. Attributes of a file Attribute Description file.closed If file is closed return true else false file.mode Returns one of the modes in which the current file is opened file.name Returns the name of the file
  • 9. Example for attributes • fileread= open( “text.txt” , ”r+” ) • print (“Name of the file : ”,fileread.name) • print (“Closed or not : ”,fileread.closed) print(“opening mode : ”,fileread.mode) OUTPUT: • Name of the file : text.txt • Closed or not : False • opening mode : r+
  • 10. Opening a file • Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. Syntax: • Fileobject = open(“filename or file path” ,”access mode”) • >>> f = open("test.txt") # open file in current directory by directly specifying the name of the file. • >>> f = open("C:/Python33/README.txt") # specifying full path. • >>> f = open(“test.txt” , “r”) # open the file by mentioning file name and mode
  • 11. File opening Modes Mode Description r Opens a file for reading only. 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 placed at the end of the file. If the file does not exist, creates a new file for writing r+ Opens a file for both reading and writing. The file pointer is placed at the beginning of the file. W+ Opens a file for both reading and writing. Overwrites the 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 reading and appending. The file pointer is placed at the end of the file. If the file does not exist, creates a new file for reading and writing.
  • 12. File opening Modes Mode Description rb Opens a file for both reading in binary format. The file pointer is placed at the beginning of the file wb Opens a file for writing only in binary format.Overwrites the file if the file exists.If the file does not exist, creates a new file for writing ab Opens a file for appending in binary format. The file pointer is placed at the end of the file. If the file does not exist, creates a new file for writing
  • 13. FILE CLOSING • When the operations that are to be performed o n a opened file are finished, we have to close the file in order to release the resources. The closing is done with a built-in function close() Syntax: fileobject.close() Example: f= open(“text.txt” , “w”) #open a file #perform some operations f.close() #close the file
  • 14. Writing to a file • After opening a file, we have to perform some operations on the file. In order to write into a file, we have to open it with w mode, or a mode, or any other writing – enabling mode. write() method enables us to write any string to a opened file. Syntax: Fileobject=open(“file.txt”,”w”) Fileobject.write(“String to be written”) Example: fo = open("foo.txt", "w") fo.write( "Python is a great language.nYeah its great!!n"); print(“success”) fo.close()
  • 15. Reading a file The text files can be read in four different ways listed below: Using read Method Using readlines Method Using readline Method Syntax: read() <file variable name>.read() When size is not specified entire file is read and the contents are placed in the left hand side variable. <file variable name>.read(<size>) When size is specified , the size number of characters are read. When an empty file is read no error is displayed but an empty string is returned.
  • 16. readlines() <file variable name>.readlines(<size>) #size optional When size is not specified entire file is read and each line is added in a list. When size is specified , the lines that make up the size bytes are read.When an empty file is read no error is displayed but an empty list is returned.
  • 17. Example for all types of reading a file: Assume the content of a file: Hello Good morning We are learning python Its very interesting
  • 18. Program fileread = open(“text.txt”, “r”) Str=fileread.read(10) Length=len(Str) print (str) print (Length) Str=fileread.read(20) print (str) Str= fileread.read() print (str) Str=fileread.readlines() print(Str) fileread.close()
  • 19. Output: Hello Good 10 morning We are learn ing python Its very interesting Hello Good morning We are learning python Its very interesting
  • 20. Renaming a file An existing file can be renamed by using the method rename() Syntax: os.rename(current filename, new filename) Example: >>> import os >>>os.rename(“C:/Python27/myfile.txt”, “C:/Python27/myfile1.txt”)
  • 21. Deleting a File An existing file can be deleted by using the method remove(). Syntax: os.remove(filename) Example: >>> import os >>>os.remove(“C:/Python27/myfile1.txt”)
  • 22. Format Operator • Definition: The format operator is used to print the output in a desired format. The % operator is the format operator. It is also called as interpolation operator. The % operator is also used for modulus. The usage varies according to the operands of the operator.
  • 23. General syntax: <format expression>%(values) # The values is a tuple with exactly the number of items specified by the format expression.
  • 24. PROGRAM print(“%d” %(45)) print(“%f”%(3.14159265358979)) print(“%0.2f”%(3.141592653589)) print (“Decimal : %u”%(24)) Print (“Octal : %o”%(24)) Print (“Hexadecimal : %x”%(1254)) Print (“Hexadecimal : %X”%(1254)) X=40 print(“The given integer is %d”%X)
  • 25. OUTPUT 45 3.141592 3.14 Decimal : 24 Octal : 30 Hexadecimal : 4e6 Hexadecimal : 4E6