0% found this document useful (0 votes)
7 views

Week 04 - Lecture - Text File Handling V2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 04 - Lecture - Text File Handling V2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

File Handling

Text Files

By Nishan Saliya IIT 1


What is a File?

 When computer store data in hard disk, they are stored in the form of a file
 A computer file can be,
 An audio file
 A video file
 A text file
 Etc.
 Python allows accessing these files and manipulating them

By Nishan Saliya IIT 2


File Access in Python

 Files can be text files or binary files


 Files can be opened with some options such as,
 Read only
 Write only
 Append only
 Read and/or write

By Nishan Saliya IIT 3


Some Text File Open Modes
Modes Details

r Reading only. The file pointer at the BOF

r+ For reading and writing. The file pointer at the BOF


Writing only. If file exists, it’ll be overwritten; If it doesn't a new file will be
w created for writing.
For writing and reading. If file exists, it’ll be overwritten; If it doesn't a new file
w+ will be created for reading and writing.

Appending. The file pointer is at EOF if the file exists. If the file does not exist,
a it creates a new file for writing.

For appending and reading. The file pointer is at EOF if the file exists. If the file
a+ does not exist, it creates a new file for reading and writing.

By Nishan Saliya IIT 4


A Simple File Read You need some
sample text files
to test this!

By Nishan Saliya IIT 5


A Simple File Read (with a Sub Folder)
Based on the system, you
may access Sub folders
with below characters
\
\\
/
//

You need some


sample text files
to test this!

By Nishan Saliya IIT 6


Sample Program to Write to a File

By Nishan Saliya IIT 7


Sample Program to Append a File

By Nishan Saliya IIT 8


Reading a File – Line by Line

By Nishan Saliya IIT 9


Reading a File – Character by Character

By Nishan Saliya IIT 10


Seek a File - Part 1

By Nishan Saliya IIT 11


Seek a File - Part 2

By Nishan Saliya IIT 12


How Seeking is Working (Windows OS)

By Nishan Saliya IIT 13


Extra Note

 CR, LF, and CRLF


 CR – Carriage Return - \r
 Used in old Mac Systems
 LF – Line Feed - \n
 Used in Unix, modrn macOS and Linux
 CRLF - Carriage Return Line Feed - \r\n
 Windows standard

 This will affect the formatting when files are shared among systems!

By Nishan Saliya IIT 14


Reference

 https://www.w3schools.com/python/python_file_handling.asp

By Nishan Saliya IIT 15

You might also like