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

More Related Content

What's hot

File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.net
Everywhere
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
MelkamuEndale1
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
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
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Docparser integration with odoo erp
Docparser integration with odoo erpDocparser integration with odoo erp
Docparser integration with odoo erp
Celine George
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
Haresh Jaiswal
 
File handling
File handlingFile handling
File handling
muhammad sharif bugti
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
Java File I/O
Java File I/OJava File I/O
Java File I/O
Canterbury HS
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
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
 
Java
JavaJava
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
Vishal Dutt
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 

What's hot (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 to H file handling

FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini 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 here
sidbhat290907
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha 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).ppt
Raja Ram Dutta
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
File Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handlingFile Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handling
abdulsamadbrohi461
 
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
Keerty Smile
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
samkinggraphics19
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
ShaswatSurya
 

Similar to 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
 
File Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handlingFile Handlingb in java. A brief presentation on file handling
File Handlingb in java. A brief presentation on file handling
 
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
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 

More from missstevenson01

The Processor.pptx
The Processor.pptxThe Processor.pptx
The Processor.pptx
missstevenson01
 
How Computers Work
How Computers WorkHow Computers Work
How Computers Work
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.pptx
missstevenson01
 
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
missstevenson01
 
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
missstevenson01
 
Lesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptxLesson2 - Coding with Minecraft - Events.pptx
Lesson2 - Coding with Minecraft - Events.pptx
missstevenson01
 
Ethical hacking trojans, worms and spyware
Ethical hacking    trojans, worms and spywareEthical hacking    trojans, worms and spyware
Ethical hacking trojans, worms and spyware
missstevenson01
 
Ethical hacking anti virus
Ethical hacking   anti virusEthical hacking   anti virus
Ethical hacking anti virus
missstevenson01
 
Ethical hacking introduction to ethical hacking
Ethical hacking   introduction to ethical hackingEthical hacking   introduction to ethical hacking
Ethical hacking introduction to ethical hacking
missstevenson01
 
S1 internet safety-chattingonline
S1 internet safety-chattingonlineS1 internet safety-chattingonline
S1 internet safety-chattingonline
missstevenson01
 
S3 wireframe diagrams
S3 wireframe diagramsS3 wireframe diagrams
S3 wireframe diagrams
missstevenson01
 
Video Games and Copyright laws
Video Games and Copyright lawsVideo Games and Copyright laws
Video Games and Copyright laws
missstevenson01
 
Games Design Document
Games Design DocumentGames Design Document
Games Design Document
missstevenson01
 
Video game proposal
Video game proposalVideo game proposal
Video game proposal
missstevenson01
 
Evaluation
EvaluationEvaluation
Evaluation
missstevenson01
 
H evaluation
H evaluationH evaluation
H evaluation
missstevenson01
 
H testing and debugging
H testing and debuggingH testing and debugging
H testing and debugging
missstevenson01
 

More from 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
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 

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