SlideShare a Scribd company logo
1 of 10
Reading and Writing Files
Using Files for Data Storage
• Allows data to be retained between program runs
▫ It’s lost when a local variable goes out of scope or when the
program terminates
 Computers store files on secondary storage devices
 hard disks, optical disks, flash drives and magnetic tapes.
 Data maintained in files is persistent data because it exists beyond
the duration of program execution.
• Used in many applications:
▫ Word processing, Image Editors, Databases, Spreadsheets,
Compilers, Games and Web Browsers
• File: a set of data stored on a computer, often on a disk drive
▫ Programs can read from and/or write to files
• Steps:
▫ Open the file
▫ Use the file (read from, write to, or both)
▫ Close the file
Data Hierarchy
 The smallest data item in a computer can assume the value
0 or 1.
 Such data items are called bits
 Python uses Unicode characters that are composed of two
bytes, each composed of eight bits(lang)
 Fields are composed of characters or bytes.
 Data items processed by computers form a data hierarchy
that becomes larger and more complex in structure as we
progress from bits to characters to fields, and so on.
• Typically, several fields compose a record (implemented
as a class in Java).
• A file is a group of related records.  Database
Opening a File Stream
• The first part of read/write a file is to create a
stream to the file.
▫ A stream is a one way path for information to
travel
▫ Code: varName = open(fileName, mode)
Ex.
fileWrite = open(“test.txt”,”w”)
input=open(“c:pytst.txt”,”r”)
Writing Files
• To write to a file use the file stream name like a
variable with the write function.
▫ Code: write(str)
Ex.
output = open(“city.txt”)
output.write(“blah blah blahn”)
Note: Loops can be used to write numerous values
to a file
Reading Files
• Reading a file is similar to writing a file in that
you use the file stream name followed by one of
the read functions.
▫ Code: read() – reads all characters from a file
read(#) – read a number of characters
readline() – reads all characters up to and
including n
readlines() – reads all lines
Reading Data From a File
• Two main ways to read data from a file:
▫ 1. While loop that iterates to the end of the file
 Code: line = infile.readline()
while line != ‘’:
#process line here
line = infile.readline()
▫ 2. A enhanced for loop
 Code: for varname in fileName
#process the line here
Closing a File Stream
• Clean up is a necessary and essential step.
• Just like when you make a mess, life will go on
but there are implications of not cleaning up.
• Ensure you close a stream after you have
processed all of your data.
▫ Code: fileStream.close()
Reading and Writing Files Example
def main():
# Prompt the user to enter filenames
f1 = input("Enter a source file: ").strip()
f2 = input("Enter a target file: ").strip()
# Open files for input and output
infile = open(f1, "r")
outfile = open(f2, "w")
# Copy from input file to output file
countLines = countChars = 0
for line in infile:
countLines += 1
countChars += len(line)
outfile.write(line)
print(countLines, "lines and", countChars, "chars copied")
infile.close() # Close the input file
outfile.close() # Close the output file
main() # Call the main function
Checkpoint
• 1. What are the 3 phases to a file stream?
• 2. What are some different ways to setup your
file stream?
• 3. What are the key differences between a read
and write file stream?

More Related Content

What's hot (20)

Interface in java
Interface in javaInterface in java
Interface in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java package
Java packageJava package
Java package
 
File Pointers
File PointersFile Pointers
File Pointers
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Javascript
JavascriptJavascript
Javascript
 
Java threads
Java threadsJava threads
Java threads
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 

Viewers also liked

Processing Regex Python
Processing Regex PythonProcessing Regex Python
Processing Regex Pythonprimeteacher32
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressionsprimeteacher32
 
More Pattern Matching With RegEx
More Pattern Matching With RegExMore Pattern Matching With RegEx
More Pattern Matching With RegExprimeteacher32
 
Processing with Regular Expressions
Processing with Regular ExpressionsProcessing with Regular Expressions
Processing with Regular Expressionsprimeteacher32
 
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnov
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnovComputer Forensics: First Responder Training - Eric Vanderburg - JurInnov
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnovEric Vanderburg
 
FIRST 2006 Full-day Tutorial on Logs for Incident Response
FIRST 2006 Full-day Tutorial on Logs for Incident ResponseFIRST 2006 Full-day Tutorial on Logs for Incident Response
FIRST 2006 Full-day Tutorial on Logs for Incident ResponseAnton Chuvakin
 
ICS Review & Response
ICS Review & ResponseICS Review & Response
ICS Review & Responsedwoodwoody
 
6 Keys to Preventing and Responding to Workplace Violence
6 Keys to Preventing and Responding to Workplace Violence6 Keys to Preventing and Responding to Workplace Violence
6 Keys to Preventing and Responding to Workplace ViolenceCase IQ
 

Viewers also liked (20)

CSV File Manipulation
CSV File ManipulationCSV File Manipulation
CSV File Manipulation
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Processing Regex Python
Processing Regex PythonProcessing Regex Python
Processing Regex Python
 
Json
JsonJson
Json
 
Web Scraping
Web ScrapingWeb Scraping
Web Scraping
 
Sending Email
Sending EmailSending Email
Sending Email
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressions
 
File I/O
File I/OFile I/O
File I/O
 
More Pattern Matching With RegEx
More Pattern Matching With RegExMore Pattern Matching With RegEx
More Pattern Matching With RegEx
 
More Perl Basics
More Perl BasicsMore Perl Basics
More Perl Basics
 
Processing with Regular Expressions
Processing with Regular ExpressionsProcessing with Regular Expressions
Processing with Regular Expressions
 
Passing Arguments
Passing ArgumentsPassing Arguments
Passing Arguments
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Incident Response in the wake of Dear CEO
Incident Response in the wake of Dear CEOIncident Response in the wake of Dear CEO
Incident Response in the wake of Dear CEO
 
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnov
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnovComputer Forensics: First Responder Training - Eric Vanderburg - JurInnov
Computer Forensics: First Responder Training - Eric Vanderburg - JurInnov
 
FIRST 2006 Full-day Tutorial on Logs for Incident Response
FIRST 2006 Full-day Tutorial on Logs for Incident ResponseFIRST 2006 Full-day Tutorial on Logs for Incident Response
FIRST 2006 Full-day Tutorial on Logs for Incident Response
 
Incident Response
Incident ResponseIncident Response
Incident Response
 
ICS Review & Response
ICS Review & ResponseICS Review & Response
ICS Review & Response
 
6 Keys to Preventing and Responding to Workplace Violence
6 Keys to Preventing and Responding to Workplace Violence6 Keys to Preventing and Responding to Workplace Violence
6 Keys to Preventing and Responding to Workplace Violence
 

Similar to Reading and Writing Files (20)

IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
Data file handling
Data file handlingData file handling
Data file handling
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Python-files
Python-filesPython-files
Python-files
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 
File management in C++
File management in C++File management in C++
File management in C++
 

More from primeteacher32

More from primeteacher32 (20)

Software Development Life Cycle
Software Development Life CycleSoftware Development Life Cycle
Software Development Life Cycle
 
Variable Scope
Variable ScopeVariable Scope
Variable Scope
 
Returning Data
Returning DataReturning Data
Returning Data
 
Intro to Functions
Intro to FunctionsIntro to Functions
Intro to Functions
 
Introduction to GUIs with guizero
Introduction to GUIs with guizeroIntroduction to GUIs with guizero
Introduction to GUIs with guizero
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
Nested Loops
Nested LoopsNested Loops
Nested Loops
 
Conditional Loops
Conditional LoopsConditional Loops
Conditional Loops
 
Introduction to Repetition Structures
Introduction to Repetition StructuresIntroduction to Repetition Structures
Introduction to Repetition Structures
 
Input Validation
Input ValidationInput Validation
Input Validation
 
Windows File Systems
Windows File SystemsWindows File Systems
Windows File Systems
 
Nesting Conditionals
Nesting ConditionalsNesting Conditionals
Nesting Conditionals
 
Conditionals
ConditionalsConditionals
Conditionals
 
Intro to Python with GPIO
Intro to Python with GPIOIntro to Python with GPIO
Intro to Python with GPIO
 
Variables and Statements
Variables and StatementsVariables and Statements
Variables and Statements
 
Variables and User Input
Variables and User InputVariables and User Input
Variables and User Input
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Raspberry Pi
Raspberry PiRaspberry Pi
Raspberry Pi
 
Hardware vs. Software Presentations
Hardware vs. Software PresentationsHardware vs. Software Presentations
Hardware vs. Software Presentations
 
Block chain security
Block chain securityBlock chain security
Block chain security
 

Recently uploaded

Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012rehmti665
 
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfNPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfDivyeshPatel234692
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceSanjay Bokadia
 
Internshala Student Partner 6.0 Jadavpur University Certificate
Internshala Student Partner 6.0 Jadavpur University CertificateInternshala Student Partner 6.0 Jadavpur University Certificate
Internshala Student Partner 6.0 Jadavpur University CertificateSoham Mondal
 
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...Suhani Kapoor
 
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...Suhani Kapoor
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳anilsa9823
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士obuhobo
 
The Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdfThe Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdftheknowledgereview1
 
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiVIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiSuhani Kapoor
 
Call Girl in Low Price Delhi Punjabi Bagh 9711199012
Call Girl in Low Price Delhi Punjabi Bagh  9711199012Call Girl in Low Price Delhi Punjabi Bagh  9711199012
Call Girl in Low Price Delhi Punjabi Bagh 9711199012sapnasaifi408
 
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...Suhani Kapoor
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjLewisJB
 
Preventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxPreventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxGry Tina Tinde
 
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Madekojalkojal131
 
Notes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testsNotes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testspriyanshukumar97908
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...shivangimorya083
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girlsshivangimorya083
 

Recently uploaded (20)

Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
 
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfNPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector Experience
 
Internshala Student Partner 6.0 Jadavpur University Certificate
Internshala Student Partner 6.0 Jadavpur University CertificateInternshala Student Partner 6.0 Jadavpur University Certificate
Internshala Student Partner 6.0 Jadavpur University Certificate
 
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
 
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
 
The Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdfThe Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdf
 
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiVIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
 
Call Girl in Low Price Delhi Punjabi Bagh 9711199012
Call Girl in Low Price Delhi Punjabi Bagh  9711199012Call Girl in Low Price Delhi Punjabi Bagh  9711199012
Call Girl in Low Price Delhi Punjabi Bagh 9711199012
 
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbj
 
Preventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxPreventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptx
 
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
 
Notes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testsNotes of bca Question paper for exams and tests
Notes of bca Question paper for exams and tests
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
 

Reading and Writing Files

  • 2. Using Files for Data Storage • Allows data to be retained between program runs ▫ It’s lost when a local variable goes out of scope or when the program terminates  Computers store files on secondary storage devices  hard disks, optical disks, flash drives and magnetic tapes.  Data maintained in files is persistent data because it exists beyond the duration of program execution. • Used in many applications: ▫ Word processing, Image Editors, Databases, Spreadsheets, Compilers, Games and Web Browsers • File: a set of data stored on a computer, often on a disk drive ▫ Programs can read from and/or write to files • Steps: ▫ Open the file ▫ Use the file (read from, write to, or both) ▫ Close the file
  • 3. Data Hierarchy  The smallest data item in a computer can assume the value 0 or 1.  Such data items are called bits  Python uses Unicode characters that are composed of two bytes, each composed of eight bits(lang)  Fields are composed of characters or bytes.  Data items processed by computers form a data hierarchy that becomes larger and more complex in structure as we progress from bits to characters to fields, and so on. • Typically, several fields compose a record (implemented as a class in Java). • A file is a group of related records.  Database
  • 4. Opening a File Stream • The first part of read/write a file is to create a stream to the file. ▫ A stream is a one way path for information to travel ▫ Code: varName = open(fileName, mode) Ex. fileWrite = open(“test.txt”,”w”) input=open(“c:pytst.txt”,”r”)
  • 5. Writing Files • To write to a file use the file stream name like a variable with the write function. ▫ Code: write(str) Ex. output = open(“city.txt”) output.write(“blah blah blahn”) Note: Loops can be used to write numerous values to a file
  • 6. Reading Files • Reading a file is similar to writing a file in that you use the file stream name followed by one of the read functions. ▫ Code: read() – reads all characters from a file read(#) – read a number of characters readline() – reads all characters up to and including n readlines() – reads all lines
  • 7. Reading Data From a File • Two main ways to read data from a file: ▫ 1. While loop that iterates to the end of the file  Code: line = infile.readline() while line != ‘’: #process line here line = infile.readline() ▫ 2. A enhanced for loop  Code: for varname in fileName #process the line here
  • 8. Closing a File Stream • Clean up is a necessary and essential step. • Just like when you make a mess, life will go on but there are implications of not cleaning up. • Ensure you close a stream after you have processed all of your data. ▫ Code: fileStream.close()
  • 9. Reading and Writing Files Example def main(): # Prompt the user to enter filenames f1 = input("Enter a source file: ").strip() f2 = input("Enter a target file: ").strip() # Open files for input and output infile = open(f1, "r") outfile = open(f2, "w") # Copy from input file to output file countLines = countChars = 0 for line in infile: countLines += 1 countChars += len(line) outfile.write(line) print(countLines, "lines and", countChars, "chars copied") infile.close() # Close the input file outfile.close() # Close the output file main() # Call the main function
  • 10. Checkpoint • 1. What are the 3 phases to a file stream? • 2. What are some different ways to setup your file stream? • 3. What are the key differences between a read and write file stream?