SlideShare una empresa de Scribd logo
1 de 29
File Handling
Software Development
Learning Intentions
By the end of this lesson learners will be able to:
❏ Open sequential text files
❏ Read from sequential text files
❏ Write to sequential text files
❏ Close text files
Saving data
You will have to save data at some point in your program.
There are various ways to do this:
❏ Files
❏ In the Registry
❏ In Databases
At Higher we will concentrate only on text/csv files.
There are various methods to access files in Python but we will be using the methods in
the File Object
Text File operations
Opening/Creating
When a text file is opened for access or a new empty file is created
Reading/Writing
When data is read from or written to a file
Closing
The file is closed and no further operations can take place
Opening Files
When a file is opened you have to specify how it should be opened
This is what type of access you will be using
When opening a file we can set the following modes
❏ Reading (default)
❏ Writing
❏ Appending
Some Python File Access Modes
Character Description
‘r’ Open for reading (default)
‘w’ Open for writing, truncating the file first
‘x’ Open for exclusive creation, failing if the file already
exists
‘a’ Open for writing, appending to the end of the file if it
exists
File Access Modes
Reading (r)
Opens the file if it exists and seeks to the end of the file, or creates a new file.
(default)
Writing (w)
Opens a file for writing, will create a new file if none exists
Reading and writing (r+)
Opens a file to read and write, will overwrite an existing file or create a new
one
Appending (a)
Opens an existing file to append, will append to the end of the file
File Reading Example Pseudocode
#-------------Main Program-----------------
OPEN FILE(SAMPLEFILE.txt) FOR READING
Filecontents = FILE.READ
CLOSE FILE
File exists in the
same folder as the
Python Program
File Reading Example Python
#-------------Main Program-----------------
with open("SampleFile.txt") as readfile:
filecontents = readfile.read()
print(filecontents)
File is automatically closed once the loop ends.
Remember to put Close File in exam situations
This would open the file for
reading
Different ways to read from a file
There are different ways to read the contents of a file
ReadLine
Reads a single line of characters from the file and returns the data as a string
Read
Reads all characters from the current position to the end of the stream
Different ways to write to a file
There are different ways to write to a file
Write - Writes a character to the stream
WriteLines(sequence) - Writes a sequence of strings to a file
Writing to a file example
#-------------Main Program-----------------
#open file
with open("newfile.txt","w") as writefile:
writefile.write("Python is great fun")
What about if you are reading a file like this
File Contents:
Joe,4
Joanna,40
Michael,50
etc..
This type of file can be known as a Comma Separated Values (CSV) file
It is just a plain text file where the text is delimited by a comma with each record usually
on a new line
Names and Ages
Processing comma separated files
Our file looks like:
Joe,80
Anna,83
We have to read and process the file in a particular manner
We will create two parallel arrays of 50 elements to store the names and
ages
We will need to process the file line by line
Then process the file using the comma as a separator
The different values are separated by a comma
Each record is on a different line
How to do this
1. We will create an two empty arrays of 50 elements
names[None] * 50
marks[None] * 50
1. While there is more text in the file we will read each line into a variable called line
2. Split the line where there is a comma using the split method
3. Each item will then be stored in a newly created array called items
4. Store the data into parallel arrays for names and marks
Items Array
Element Value
0 Joe
1 80name Array
Element Value
0 Joe
marks Array
Element Value
0 80
Joe,80
Anna,83
Example – Reading from a csv file
counter = 0
names = [None] * 50
marks = [None] * 50
with open("marks.txt") as readfile:
#read in a single line of the file and remove the end of line character
line = readfile.readline().rstrip('n')
#While there are more lines of text
while line:
items = line.split(",")
names[counter] = items[0]
Marks[counter] = items[1]
line = readfile.readline().rstrip('n')
counter += 1
split the line of text where there is a comma
each item will be stored in a separate element of
a list
the first element of the list will contain the name -
assign this to the names array
the second element of the list will contain
the mark, assign this to the names array
read in the next line of the file
Walk Through Step 1
Initialise the variable counter and the names and
marks arrays
Items Array
0
1
marks Array
0
name Array
0
line variable
counter
0
Joe,80
Anna,83
Walk Through Step 2
Open the File
Items Array
0
1
marks Array
0
name Array
0
line variable
counter
0
Joe,80
Anna,83
Walk Through Step 3
Read the first line of the file, stripping the new line character n
Items Array
0
1
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
Walk Through Step 4
While this line of text isn’t empty (there are some contents in the file)
Items Array
0
1
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
Walk Through Step 5
Split the text in the variable called line on any comma and store it the items array
Items Array
0 Joe
1 80
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
Walk Through Step 6
Place the first value in the Items array into the first value of the names array
Items Array
0 Joe
1 80
marks Array
0
name Array
0 Joe
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
Walk Through Step 7
Place the second value in the Items array into the first value of the names array
Items Array
0 Joe
1 80
marks Array
0 80
name Array
0 Joe
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
Walk Through Step 8
Read the second line of the file, stripping the new line character n
Items Array
0 Joe
1 83
marks Array
0 83
name Array
0 Joe
line variable
“Anna,83”
counter
0
Joe,80
Anna,83
Walk Through Step 9
Increment the counter variable so that new items will be placed at element 1 in the names and marks arrays
Items Array
0 Joe
1 83
marks Array
0 83
name Array
0 Joe
line variable
“Anna,83”
counter
1
Joe,80
Anna,83
Creating a csv File using variables
for counter in range(5):
name = input("Enter name: ")
age = input("Enter age: ")
with open("names.txt","w") as writefile:
writefile.write(name + ","+ str(age) + "n")
Writes that detail on one line
File mode set to writing
Creating a csv File from arrays
names = ["John","Anna","Mark","Michael"]
ages = [23,35,23,8]
with open("names.txt","w") as wfile:
for counter in range(len(names)):
wfile.write(names[counter] + ","+ str(ages[counter])+"n")
Puts an end of line character at
the end of the line
name Array
Element Value
0 John
1 Joan
ages Array
Element Value
0 23
1 35
John,23
Anna,35
Using records to write to files
For the next slide we will assume the following record structure shown below
And that we have an array of these member records called clubmembers which has 50
elements. A sample of the data is shown below to the right
Record Structure
RECORD member:
name :
STRING
age:
INTEGER
END RECORD
Record
Number
name age
0 John 23
1 Anna 35
Creating a csv File from records
with open("names.txt","w") as wfile:
for i in range(len(clubmembers)):
wfile.write(clubmembers[i].name + ","+ str(clubmembers[i].ages[i])+"n")
John,23
Anna,35
Record
Number
name age
0 John 23
1 Anna 35

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.net
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
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
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Docparser integration with odoo erp
Docparser integration with odoo erpDocparser integration with odoo erp
Docparser integration with odoo erp
 
File handling
File handlingFile handling
File handling
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
File handling
File handlingFile handling
File handling
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Java File I/O
Java File I/OJava File I/O
Java File I/O
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
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
 
Java
JavaJava
Java
 
File Handling
File HandlingFile Handling
File Handling
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Cis166 final review c#
Cis166 final review c#Cis166 final review c#
Cis166 final review c#
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 

Similar a H file handling

FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
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 heresidbhat290907
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxssuserd0df33
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
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
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptxAmitKaur17
 
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 methodsKeerty Smile
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdfbotin17097
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 

Similar a H file handling (20)

FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
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
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
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.
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Python-files
Python-filesPython-files
Python-files
 
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 file handling
Python file handlingPython file handling
Python file handling
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 

Más de missstevenson01

Lesson 3 - Coding with Minecraft - Variables.pptx
Lesson 3 -  Coding with Minecraft -  Variables.pptxLesson 3 -  Coding with Minecraft -  Variables.pptx
Lesson 3 - Coding with Minecraft - Variables.pptxmissstevenson01
 
Lesson 2 - Coding with Minecraft - Events.pptx
Lesson 2 - Coding with Minecraft - Events.pptxLesson 2 - Coding with Minecraft - Events.pptx
Lesson 2 - Coding with Minecraft - Events.pptxmissstevenson01
 
Lesson 1 - Coding with Minecraft -Introduction.pptx
Lesson 1 - Coding with Minecraft -Introduction.pptxLesson 1 - Coding with Minecraft -Introduction.pptx
Lesson 1 - Coding with Minecraft -Introduction.pptxmissstevenson01
 
Lesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptxLesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptxmissstevenson01
 
Ethical hacking trojans, worms and spyware
Ethical hacking    trojans, worms and spywareEthical hacking    trojans, worms and spyware
Ethical hacking trojans, worms and spywaremissstevenson01
 
Ethical hacking anti virus
Ethical hacking   anti virusEthical hacking   anti virus
Ethical hacking anti virusmissstevenson01
 
Ethical hacking introduction to ethical hacking
Ethical hacking   introduction to ethical hackingEthical hacking   introduction to ethical hacking
Ethical hacking introduction to ethical hackingmissstevenson01
 
S1 internet safety-chattingonline
S1 internet safety-chattingonlineS1 internet safety-chattingonline
S1 internet safety-chattingonlinemissstevenson01
 
Video Games and Copyright laws
Video Games and Copyright lawsVideo Games and Copyright laws
Video Games and Copyright lawsmissstevenson01
 

Más de missstevenson01 (20)

S3 environment
S3 environmentS3 environment
S3 environment
 
The Processor.pptx
The Processor.pptxThe Processor.pptx
The Processor.pptx
 
How Computers Work
How Computers WorkHow Computers Work
How Computers Work
 
Lesson 3 - Coding with Minecraft - Variables.pptx
Lesson 3 -  Coding with Minecraft -  Variables.pptxLesson 3 -  Coding with Minecraft -  Variables.pptx
Lesson 3 - Coding with Minecraft - Variables.pptx
 
Lesson 2 - Coding with Minecraft - Events.pptx
Lesson 2 - Coding with Minecraft - Events.pptxLesson 2 - Coding with Minecraft - Events.pptx
Lesson 2 - Coding with Minecraft - Events.pptx
 
Lesson 1 - Coding with Minecraft -Introduction.pptx
Lesson 1 - Coding with Minecraft -Introduction.pptxLesson 1 - Coding with Minecraft -Introduction.pptx
Lesson 1 - Coding with Minecraft -Introduction.pptx
 
Lesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptxLesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptx
 
Ethical hacking trojans, worms and spyware
Ethical hacking    trojans, worms and spywareEthical hacking    trojans, worms and spyware
Ethical hacking trojans, worms and spyware
 
Ethical hacking anti virus
Ethical hacking   anti virusEthical hacking   anti virus
Ethical hacking anti virus
 
Ethical hacking introduction to ethical hacking
Ethical hacking   introduction to ethical hackingEthical hacking   introduction to ethical hacking
Ethical hacking introduction to ethical hacking
 
S1 internet safety-chattingonline
S1 internet safety-chattingonlineS1 internet safety-chattingonline
S1 internet safety-chattingonline
 
S3 wireframe diagrams
S3 wireframe diagramsS3 wireframe diagrams
S3 wireframe diagrams
 
Sql
SqlSql
Sql
 
Alien database
Alien databaseAlien database
Alien database
 
Video Games and Copyright laws
Video Games and Copyright lawsVideo Games and Copyright laws
Video Games and Copyright laws
 
Games Design Document
Games Design DocumentGames Design Document
Games Design Document
 
Video game proposal
Video game proposalVideo game proposal
Video game proposal
 
Evaluation
EvaluationEvaluation
Evaluation
 
H evaluation
H evaluationH evaluation
H evaluation
 
H testing and debugging
H testing and debuggingH testing and debugging
H testing and debugging
 

Último

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
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
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
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
 
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
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Último (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.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
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
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
 
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
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

H file handling

  • 2. Learning Intentions By the end of this lesson learners will be able to: ❏ Open sequential text files ❏ Read from sequential text files ❏ Write to sequential text files ❏ Close text files
  • 3. Saving data You will have to save data at some point in your program. There are various ways to do this: ❏ Files ❏ In the Registry ❏ In Databases At Higher we will concentrate only on text/csv files. There are various methods to access files in Python but we will be using the methods in the File Object
  • 4. Text File operations Opening/Creating When a text file is opened for access or a new empty file is created Reading/Writing When data is read from or written to a file Closing The file is closed and no further operations can take place
  • 5. Opening Files When a file is opened you have to specify how it should be opened This is what type of access you will be using When opening a file we can set the following modes ❏ Reading (default) ❏ Writing ❏ Appending
  • 6. Some Python File Access Modes Character Description ‘r’ Open for reading (default) ‘w’ Open for writing, truncating the file first ‘x’ Open for exclusive creation, failing if the file already exists ‘a’ Open for writing, appending to the end of the file if it exists
  • 7. File Access Modes Reading (r) Opens the file if it exists and seeks to the end of the file, or creates a new file. (default) Writing (w) Opens a file for writing, will create a new file if none exists Reading and writing (r+) Opens a file to read and write, will overwrite an existing file or create a new one Appending (a) Opens an existing file to append, will append to the end of the file
  • 8. File Reading Example Pseudocode #-------------Main Program----------------- OPEN FILE(SAMPLEFILE.txt) FOR READING Filecontents = FILE.READ CLOSE FILE File exists in the same folder as the Python Program
  • 9. File Reading Example Python #-------------Main Program----------------- with open("SampleFile.txt") as readfile: filecontents = readfile.read() print(filecontents) File is automatically closed once the loop ends. Remember to put Close File in exam situations This would open the file for reading
  • 10. Different ways to read from a file There are different ways to read the contents of a file ReadLine Reads a single line of characters from the file and returns the data as a string Read Reads all characters from the current position to the end of the stream
  • 11. Different ways to write to a file There are different ways to write to a file Write - Writes a character to the stream WriteLines(sequence) - Writes a sequence of strings to a file
  • 12. Writing to a file example #-------------Main Program----------------- #open file with open("newfile.txt","w") as writefile: writefile.write("Python is great fun")
  • 13. What about if you are reading a file like this File Contents: Joe,4 Joanna,40 Michael,50 etc.. This type of file can be known as a Comma Separated Values (CSV) file It is just a plain text file where the text is delimited by a comma with each record usually on a new line Names and Ages
  • 14. Processing comma separated files Our file looks like: Joe,80 Anna,83 We have to read and process the file in a particular manner We will create two parallel arrays of 50 elements to store the names and ages We will need to process the file line by line Then process the file using the comma as a separator The different values are separated by a comma Each record is on a different line
  • 15. How to do this 1. We will create an two empty arrays of 50 elements names[None] * 50 marks[None] * 50 1. While there is more text in the file we will read each line into a variable called line 2. Split the line where there is a comma using the split method 3. Each item will then be stored in a newly created array called items 4. Store the data into parallel arrays for names and marks Items Array Element Value 0 Joe 1 80name Array Element Value 0 Joe marks Array Element Value 0 80 Joe,80 Anna,83
  • 16. Example – Reading from a csv file counter = 0 names = [None] * 50 marks = [None] * 50 with open("marks.txt") as readfile: #read in a single line of the file and remove the end of line character line = readfile.readline().rstrip('n') #While there are more lines of text while line: items = line.split(",") names[counter] = items[0] Marks[counter] = items[1] line = readfile.readline().rstrip('n') counter += 1 split the line of text where there is a comma each item will be stored in a separate element of a list the first element of the list will contain the name - assign this to the names array the second element of the list will contain the mark, assign this to the names array read in the next line of the file
  • 17. Walk Through Step 1 Initialise the variable counter and the names and marks arrays Items Array 0 1 marks Array 0 name Array 0 line variable counter 0 Joe,80 Anna,83
  • 18. Walk Through Step 2 Open the File Items Array 0 1 marks Array 0 name Array 0 line variable counter 0 Joe,80 Anna,83
  • 19. Walk Through Step 3 Read the first line of the file, stripping the new line character n Items Array 0 1 marks Array 0 name Array 0 line variable “Joe,80” counter 0 Joe,80 Anna,83
  • 20. Walk Through Step 4 While this line of text isn’t empty (there are some contents in the file) Items Array 0 1 marks Array 0 name Array 0 line variable “Joe,80” counter 0 Joe,80 Anna,83
  • 21. Walk Through Step 5 Split the text in the variable called line on any comma and store it the items array Items Array 0 Joe 1 80 marks Array 0 name Array 0 line variable “Joe,80” counter 0 Joe,80 Anna,83
  • 22. Walk Through Step 6 Place the first value in the Items array into the first value of the names array Items Array 0 Joe 1 80 marks Array 0 name Array 0 Joe line variable “Joe,80” counter 0 Joe,80 Anna,83
  • 23. Walk Through Step 7 Place the second value in the Items array into the first value of the names array Items Array 0 Joe 1 80 marks Array 0 80 name Array 0 Joe line variable “Joe,80” counter 0 Joe,80 Anna,83
  • 24. Walk Through Step 8 Read the second line of the file, stripping the new line character n Items Array 0 Joe 1 83 marks Array 0 83 name Array 0 Joe line variable “Anna,83” counter 0 Joe,80 Anna,83
  • 25. Walk Through Step 9 Increment the counter variable so that new items will be placed at element 1 in the names and marks arrays Items Array 0 Joe 1 83 marks Array 0 83 name Array 0 Joe line variable “Anna,83” counter 1 Joe,80 Anna,83
  • 26. Creating a csv File using variables for counter in range(5): name = input("Enter name: ") age = input("Enter age: ") with open("names.txt","w") as writefile: writefile.write(name + ","+ str(age) + "n") Writes that detail on one line File mode set to writing
  • 27. Creating a csv File from arrays names = ["John","Anna","Mark","Michael"] ages = [23,35,23,8] with open("names.txt","w") as wfile: for counter in range(len(names)): wfile.write(names[counter] + ","+ str(ages[counter])+"n") Puts an end of line character at the end of the line name Array Element Value 0 John 1 Joan ages Array Element Value 0 23 1 35 John,23 Anna,35
  • 28. Using records to write to files For the next slide we will assume the following record structure shown below And that we have an array of these member records called clubmembers which has 50 elements. A sample of the data is shown below to the right Record Structure RECORD member: name : STRING age: INTEGER END RECORD Record Number name age 0 John 23 1 Anna 35
  • 29. Creating a csv File from records with open("names.txt","w") as wfile: for i in range(len(clubmembers)): wfile.write(clubmembers[i].name + ","+ str(clubmembers[i].ages[i])+"n") John,23 Anna,35 Record Number name age 0 John 23 1 Anna 35