SlideShare a Scribd company logo
Working with files
FERRY KEMPERMAN
NANJING FOREIGN LANGUAGE SCHOOL
FEBRUARY 2019
Software requires interaction with the
filesystem
READING DATA FROM A FILE
• Most algorithms require input data in
one form or another.This can be done
in three ways:
• This input data can be supplied by the
user by prompting him.
• The input data can also be read from
an existing file on the filesystem.
• The input data can be supplied by
another information system (like a
DMBS).This requires a special
interface between the two systems.
WRITING DATA TO A FILE
• Output data generated by an
algorithm can be processed in three
ways as well.
• You can prompt the user with a
message on screen.
• You can write the output data to a file
on the filesystem.This can be a new
file or appending it to an existing file.
• Output data is transferred to another
system, which requires the same
interface.
Writing data from and to a file
FILE FORMATS
• Files on a filesystem have different formats.
• A format is a structured way of how data is written to a
file.
• File formats are based on the file extension, the three
characters after the dot of a filename.
• MyLetter.doc or MyLetter.txt
• .Doc extension is a file format used by Microsoft Word to
store the contents of a letter written inWord.This is a
complex file format.
• .Txt on the is aWYSIWYG-format. It stores the exact
characters (ASCII, Unicode) in the exact order that you
write them.You can open a .txt in notepad,WYSIWYG
editor.
• What happens if you open a .doc file in notepad?Why?
WHAT ARE FILES?
• WYSIWYG =WhatYou See IsWhatYou Get.
• This a common concept in Computer Science which
refers to all the techniques related to (among others)
making and editing files and storing it in exact the same
way you see it on your screen.
• What is a file? An allocated piece of storage on
secondary memory that has a unique name, an
extension, a format and size in Bytes.
• Files can be created, deleted and modified.
• This can be done by end-users on the filesystem or by
running software (including the OS).
• Files are organized in folders.TheOS knows the exact
location of every file at any given time.The OS manages
the filesystem.
TEXT FILES
WHAT IS A TEXT FILE?
• A text file is a file that stores characters in an
order they were entered by the user.
• Every line in a text file has a control character
‘end-of-line’ to indicate that the next character
has to start on the next line.
• Every text file has an ‘end-of-file’ to indicate that
this is the last character of the file.
• This is very important!
• Why?
PROCESSING OF A TEXT FILE
• Software that writes and reads data
from text files rely on the formatting of
that file.
• It reads character by character, or a
group of characters at the same time.
• If the software encounters a /nol (end of
line character), it knows is has to look on
the next line. Otherwise the software
would have a clue!
• How does software know it read the
entire file? Right, because it encounters
the end-of-file character!
Writing to a file in pseudocode
ACTION NECESSARY
• In order to use files from a
program, we need to gain access
to the file first.This is called a file
handler.
• We specify the action we want to
invoke on that file: writing or
reading
• We perform the write action
• We release (close) the file handler.
• The OS will allow only one
application/user access to the
same file at the same time! The
file handler guarantees that!
PSEUDOCODE STATEMENT
• OPENFILE “Test.txt” FOR WRITE
• WRITEFILE “Text.txt”, “Mr.Kemperman”
• CLOSEFILE
PSEUDOCODE VS PYTHON: WRITING TO A FILE
• PSEUDOCODE
• OPENFILE “Test.txt” FORWRITE
• WRITEFILE “Text.txt”, “Mr.Kemperman”
• CLOSEFILE
• PYTHON
• FileHandle = open(“Test.txt”, “w”)
• FileHandle.write(“Mr.Kemperman”)
• FileHandle.close()
• open, write and close are functions.
• IfTest.txt exists, the file will be deleted and recreated
as soon as you open the file using the first statement!
• In this case the string “Mr.Kemperman” will be on the
first line of the text file!
• If you want to append data to an existing file you need
to use the keyword APPEND instead ofWRITE
PSEUDOCODE VS PYTHON: ADDING TO AN
EXISTING FILE (APPEND)
• PSEUDOCODE
• OPENFILE “Test.txt” FOR APPEND
• WRITEFILE “Text.txt”, “Mr.Kemperman”
• CLOSEFILE
• PYTHON
• FileHandle = open(“Test.txt”, “a”)
• FileHandle.write(“Mr.Kemperman”)
• FileHandle.close()
• IfTest.txt exists, the file will be kept, opened and
the string “Mr.Kemperman” will be on the next
line of the text file!
• If you want to append data to an existing file you
need to use the keyword APPEND instead of
WRITE
READING FROM AN EXISTING FILE
• Reading from an existing file
works as follows:
• Declare a variable in which you are
going to store the string read from
the file!
• Open the file by assigning a read
handler
• Read one line of characters from
the file and store it in a variable.
• Close the file handler
• PSEUDOCODE
• DECLARE MyFileContent : STRING
• MyFileContent  “”
• OPENFILE “Test.txt” FOR READ
• READFILE “Test.txt”, MyFileContent
• CLOSEFILE
READING: PSEUDOCODE VS PYTHON
• PSEUDOCODE
• DECLARE MyFileContent :
STRING
• MyFileContent  “”
• OPENFILE “Test.txt” FOR
READ
• READFILE “Test.txt”,
MyFileContent
• CLOSEFILE
• PYTHON
• No declaration necessary in Python, but
use commenting!!
• FileHandle = open(“Test.txt”,”r”)
• MyFileContent = FileHandle.readline()
• FileHandle.close()
End-of-Line and End-of-File markers
• If you read or write to files you need to know when data appears on a new line and
when all the data in the text file is read.
• In order the recognize the end of a line and the end of a file, we need a special
control character (not visible, but it is there and has its own ASCIIcode) that is
stored in a text file.
• End-Of-Line control character, usually known as LF/CR (Line Feed/Carriage Return)
to mark the end of line.
• End-Of-File control character to mark the end of a file, literally.
• These control characters are necessary for reading and writing to files correctly and
can be used in your code!
Printing the contents of a file on the screen
• We read the file line by line and therefor display the contents of that line on the screen one by
one. How does the program now when all lines are read from the file?
• We use the EoF marker! Pseudocode solution:
• DECLARECurrentLine : STRING
• OPENFILE “Test.txt” FOR READ
• WHILE NOT EOF(“Test.txt”) // EOF is true if EoF control character is encountered, otherwise false.
• READFILE “Text.txt”, CurrentLine
• OUTPUT CurrentLine
• ENDWHILE
• CLOSEFILE “Test.txt”
PYTHON IMPLEMENTATION
• FileHandle = open(“Text.txt”,”r”)
• CurrentLine = FileHandle.readline()
• while len(LineOfText) > 0: // length of the string on current line is bigger than zero!
• CurrentLine = FileHandle.readline()
• print(CurrentLine)
• FileHandle.close
• We are using a built-in function len to test for the length of a string on a line,
since there is no built-in function in Python to test for EoL marker!
Exercise with file handling in Python.
• Design an algorithm in pseudocode and implement it in Python that does the
following:
• Create a text file called Felix.txt (your name)
• Write your full name on the first line, your age on the second line and your full
address on the third line
• After this, prove that your file contains 3 lines with the correct data (screenshot)
• Read the data from the file and display all the information on ONE line on the
screen!
• Proof that you algorithm is working correctly.
• Make a small report as we have done before.
• You can work on this in class tomorrow too.Turn it in onWednesday before class.

More Related Content

Similar to Working with files (concepts/pseudocode/python)

File management
File managementFile management
File management
sumathiv9
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
Ananthi Palanisamy
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
SureshKalirawna
 
File mangement
File mangementFile mangement
File mangement
Jigarthacker
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
Hatem Abd El-Salam
 
C files
C filesC files
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
qover
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
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
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
botin17097
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
Linga Lgs
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
Blue Elephant Consulting
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
Khushal Mehta
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
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
 

Similar to Working with files (concepts/pseudocode/python) (20)

File management
File managementFile management
File management
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
File mangement
File mangementFile mangement
File mangement
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
 
C files
C filesC files
C files
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Files in php
Files in phpFiles in php
Files in php
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
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
 

More from FerryKemperman

Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
FerryKemperman
 
Top_down_programming..............................
Top_down_programming..............................Top_down_programming..............................
Top_down_programming..............................
FerryKemperman
 
OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........
FerryKemperman
 
Search and Sort algorithms. Bubble, Insertion, Selection.
Search and Sort algorithms. Bubble, Insertion, Selection.Search and Sort algorithms. Bubble, Insertion, Selection.
Search and Sort algorithms. Bubble, Insertion, Selection.
FerryKemperman
 
Structured Query Language introduction..
Structured Query Language introduction..Structured Query Language introduction..
Structured Query Language introduction..
FerryKemperman
 
SDT introduction as given at MKIS, KL, 2023
SDT introduction as given at MKIS, KL, 2023SDT introduction as given at MKIS, KL, 2023
SDT introduction as given at MKIS, KL, 2023
FerryKemperman
 
Computer Architecture Machine Cycle (1).pdf
Computer Architecture Machine Cycle (1).pdfComputer Architecture Machine Cycle (1).pdf
Computer Architecture Machine Cycle (1).pdf
FerryKemperman
 
Referential integrity in databases.pptx
Referential integrity in databases.pptxReferential integrity in databases.pptx
Referential integrity in databases.pptx
FerryKemperman
 

More from FerryKemperman (8)

Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Top_down_programming..............................
Top_down_programming..............................Top_down_programming..............................
Top_down_programming..............................
 
OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........
 
Search and Sort algorithms. Bubble, Insertion, Selection.
Search and Sort algorithms. Bubble, Insertion, Selection.Search and Sort algorithms. Bubble, Insertion, Selection.
Search and Sort algorithms. Bubble, Insertion, Selection.
 
Structured Query Language introduction..
Structured Query Language introduction..Structured Query Language introduction..
Structured Query Language introduction..
 
SDT introduction as given at MKIS, KL, 2023
SDT introduction as given at MKIS, KL, 2023SDT introduction as given at MKIS, KL, 2023
SDT introduction as given at MKIS, KL, 2023
 
Computer Architecture Machine Cycle (1).pdf
Computer Architecture Machine Cycle (1).pdfComputer Architecture Machine Cycle (1).pdf
Computer Architecture Machine Cycle (1).pdf
 
Referential integrity in databases.pptx
Referential integrity in databases.pptxReferential integrity in databases.pptx
Referential integrity in databases.pptx
 

Recently uploaded

What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 

Recently uploaded (20)

What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 

Working with files (concepts/pseudocode/python)

  • 1. Working with files FERRY KEMPERMAN NANJING FOREIGN LANGUAGE SCHOOL FEBRUARY 2019
  • 2. Software requires interaction with the filesystem READING DATA FROM A FILE • Most algorithms require input data in one form or another.This can be done in three ways: • This input data can be supplied by the user by prompting him. • The input data can also be read from an existing file on the filesystem. • The input data can be supplied by another information system (like a DMBS).This requires a special interface between the two systems. WRITING DATA TO A FILE • Output data generated by an algorithm can be processed in three ways as well. • You can prompt the user with a message on screen. • You can write the output data to a file on the filesystem.This can be a new file or appending it to an existing file. • Output data is transferred to another system, which requires the same interface.
  • 3. Writing data from and to a file FILE FORMATS • Files on a filesystem have different formats. • A format is a structured way of how data is written to a file. • File formats are based on the file extension, the three characters after the dot of a filename. • MyLetter.doc or MyLetter.txt • .Doc extension is a file format used by Microsoft Word to store the contents of a letter written inWord.This is a complex file format. • .Txt on the is aWYSIWYG-format. It stores the exact characters (ASCII, Unicode) in the exact order that you write them.You can open a .txt in notepad,WYSIWYG editor. • What happens if you open a .doc file in notepad?Why? WHAT ARE FILES? • WYSIWYG =WhatYou See IsWhatYou Get. • This a common concept in Computer Science which refers to all the techniques related to (among others) making and editing files and storing it in exact the same way you see it on your screen. • What is a file? An allocated piece of storage on secondary memory that has a unique name, an extension, a format and size in Bytes. • Files can be created, deleted and modified. • This can be done by end-users on the filesystem or by running software (including the OS). • Files are organized in folders.TheOS knows the exact location of every file at any given time.The OS manages the filesystem.
  • 4. TEXT FILES WHAT IS A TEXT FILE? • A text file is a file that stores characters in an order they were entered by the user. • Every line in a text file has a control character ‘end-of-line’ to indicate that the next character has to start on the next line. • Every text file has an ‘end-of-file’ to indicate that this is the last character of the file. • This is very important! • Why? PROCESSING OF A TEXT FILE • Software that writes and reads data from text files rely on the formatting of that file. • It reads character by character, or a group of characters at the same time. • If the software encounters a /nol (end of line character), it knows is has to look on the next line. Otherwise the software would have a clue! • How does software know it read the entire file? Right, because it encounters the end-of-file character!
  • 5. Writing to a file in pseudocode ACTION NECESSARY • In order to use files from a program, we need to gain access to the file first.This is called a file handler. • We specify the action we want to invoke on that file: writing or reading • We perform the write action • We release (close) the file handler. • The OS will allow only one application/user access to the same file at the same time! The file handler guarantees that! PSEUDOCODE STATEMENT • OPENFILE “Test.txt” FOR WRITE • WRITEFILE “Text.txt”, “Mr.Kemperman” • CLOSEFILE
  • 6. PSEUDOCODE VS PYTHON: WRITING TO A FILE • PSEUDOCODE • OPENFILE “Test.txt” FORWRITE • WRITEFILE “Text.txt”, “Mr.Kemperman” • CLOSEFILE • PYTHON • FileHandle = open(“Test.txt”, “w”) • FileHandle.write(“Mr.Kemperman”) • FileHandle.close() • open, write and close are functions. • IfTest.txt exists, the file will be deleted and recreated as soon as you open the file using the first statement! • In this case the string “Mr.Kemperman” will be on the first line of the text file! • If you want to append data to an existing file you need to use the keyword APPEND instead ofWRITE
  • 7. PSEUDOCODE VS PYTHON: ADDING TO AN EXISTING FILE (APPEND) • PSEUDOCODE • OPENFILE “Test.txt” FOR APPEND • WRITEFILE “Text.txt”, “Mr.Kemperman” • CLOSEFILE • PYTHON • FileHandle = open(“Test.txt”, “a”) • FileHandle.write(“Mr.Kemperman”) • FileHandle.close() • IfTest.txt exists, the file will be kept, opened and the string “Mr.Kemperman” will be on the next line of the text file! • If you want to append data to an existing file you need to use the keyword APPEND instead of WRITE
  • 8. READING FROM AN EXISTING FILE • Reading from an existing file works as follows: • Declare a variable in which you are going to store the string read from the file! • Open the file by assigning a read handler • Read one line of characters from the file and store it in a variable. • Close the file handler • PSEUDOCODE • DECLARE MyFileContent : STRING • MyFileContent  “” • OPENFILE “Test.txt” FOR READ • READFILE “Test.txt”, MyFileContent • CLOSEFILE
  • 9. READING: PSEUDOCODE VS PYTHON • PSEUDOCODE • DECLARE MyFileContent : STRING • MyFileContent  “” • OPENFILE “Test.txt” FOR READ • READFILE “Test.txt”, MyFileContent • CLOSEFILE • PYTHON • No declaration necessary in Python, but use commenting!! • FileHandle = open(“Test.txt”,”r”) • MyFileContent = FileHandle.readline() • FileHandle.close()
  • 10. End-of-Line and End-of-File markers • If you read or write to files you need to know when data appears on a new line and when all the data in the text file is read. • In order the recognize the end of a line and the end of a file, we need a special control character (not visible, but it is there and has its own ASCIIcode) that is stored in a text file. • End-Of-Line control character, usually known as LF/CR (Line Feed/Carriage Return) to mark the end of line. • End-Of-File control character to mark the end of a file, literally. • These control characters are necessary for reading and writing to files correctly and can be used in your code!
  • 11. Printing the contents of a file on the screen • We read the file line by line and therefor display the contents of that line on the screen one by one. How does the program now when all lines are read from the file? • We use the EoF marker! Pseudocode solution: • DECLARECurrentLine : STRING • OPENFILE “Test.txt” FOR READ • WHILE NOT EOF(“Test.txt”) // EOF is true if EoF control character is encountered, otherwise false. • READFILE “Text.txt”, CurrentLine • OUTPUT CurrentLine • ENDWHILE • CLOSEFILE “Test.txt”
  • 12. PYTHON IMPLEMENTATION • FileHandle = open(“Text.txt”,”r”) • CurrentLine = FileHandle.readline() • while len(LineOfText) > 0: // length of the string on current line is bigger than zero! • CurrentLine = FileHandle.readline() • print(CurrentLine) • FileHandle.close • We are using a built-in function len to test for the length of a string on a line, since there is no built-in function in Python to test for EoL marker!
  • 13. Exercise with file handling in Python. • Design an algorithm in pseudocode and implement it in Python that does the following: • Create a text file called Felix.txt (your name) • Write your full name on the first line, your age on the second line and your full address on the third line • After this, prove that your file contains 3 lines with the correct data (screenshot) • Read the data from the file and display all the information on ONE line on the screen! • Proof that you algorithm is working correctly. • Make a small report as we have done before. • You can work on this in class tomorrow too.Turn it in onWednesday before class.