4 Text Files
4 Text Files
com
S.No. Topics
2 File Processing
3 DATA FILES
11 Copying a file
14 seek() method
Page 1 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
What is file?
A file is a collection of related records stored on a particular area of the
storage medium or device.
Need for File Handling:
To Store data in organized manner
To store data permanently
To access data faster
To Search data faster
To easily modify data later on
Page 2 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
DATA FILES
Python Data Files can be of two types
1) Text File 2) Binary File
Text File:
Text files are structured as a sequence of lines, where each line includes a
sequence of characters.
Each line is terminated with a special character, called the EOL or End of
Line character. In python EOL is ‘\n’ or ‘\r’ or combination of both
Binary File
In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
Operations on binary files are faster as no translation required.
Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf,
etc., all of them constitute binary files.
Page 3 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Text file
r r+ w w+ a a+ x x+
Modes
Binary file
rb rb+ wb wb+ ab ab+ xb xb+
Modes
Read ✔ ✔ ✘ ✔ ✘ ✘ ✘ ✔
Write ✘ ✔ ✔ ✔ ✔ ✔ ✔ ✔
Creates file ✘ ✘ ✔ ✔ ✔ ✔ ✔ ✔
Erases file ✘ ✘ ✔ ✔ ✘ ✘ ✘ ✘
Initial Start Start Start Start End End Start Start
position
Page 4 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
file_name
File_name is a mandatory argument that you have to provide to
the open function
While rest all arguments are optional and use their default values.
To put it simply, the file argument represents the path where your file resides
in your system.
access_mode (optional argument)
Page 5 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Only contains the name of the file. This can be used when the file that you are trying
to open is in the same directory or folder as the Python program resides/ saves.
Example 2: Open a file in write mode
Myfile = open("D:\Amjad_CS\Story1.txt",‘w’)# specifying full path
Then we need to use a specific path to tell the function that the file is within
another folder.
The ‘r’ makes the string raw, that is, it tells that the string is without any special
characters. The ‘r’ can be ignored if the file is in same directory and address is not
being placed.
Page 6 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
– We do this for all files – ones that we opened for writing, reading, or
appending or
myFileObject .close()
Example: Opening and Closing a file "Story1.txt" for object name Myfile.
Myfile = open ("D:\Amjad_CS\Story1.txt",‘w’)
Myfile. close()
1. write()
2. writelines(list)
Page 7 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Example: Writes the String ‘Hello Python’ into the ‘learnpython4cbse.txt’ file.
Example: The first line will be ‘Hello Python’ and as we have mentioned \n
character, the cursor will move to the next line of the file and then write ‘Learn
with fun’ with new line character \n and in third line write ‘Python Magic’
Note: Remember if we don’t mention \n character, then the data will be written
continuously in the text file like ‘Learn with funPython Magic’
Page 8 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Page 9 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
1. .read(size):
This reads from the file based on the number of size bytes. If no argument is passed
or None or -1 is passed, then the entire file is read.
Syntax: fileObj.read(size)
Example: Read and print the entire file “learnpython4cbse.txt”
OUTPUT:
Page 10 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
CODING OUTPUT
Example: Read and print the first 20 character of second line from a file
using readline( ) method
CODING OUTPUT
3. .readlines(size)
It is used to read all the lines at a single go and then return them as each line a
string element in a list.
Page 11 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
OUTPUT:
Example 1: Use the readline() to read further. If the file is not empty
keep reading one line at a time, till the file is empty
TYPE -1 TYPE -II
OR
Page 12 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Page 13 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
OUTPUT: The output is same for all examples (1-3) and use of with
block
So, you can Read a Text File Line by Line using any one of the methods as we
discussed above.
Page 14 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Page 15 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
1. Open StudentRecord.txt in
read text rt mode and get the
reference to fileRead.
Open NewStudentRecord.txt in
write text wt mode and get the
reference to newfile
Page 16 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
In the following example, we will replace the string Ahil with ashaz in
StudentRecord.txt file, and overwrite the StudentRecord.txt file with the replaced
text.
Page 17 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Example: The program copies the contents of one file and writes it into another.
Steps to follow:
Steps to follow:
Open file in read and write mode, get all the data from the file and close it. OR
open file in with block in read and write mode.
Read the content in new_f object and compare with the given string
Page 18 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
OUTPUT:
Page 19 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
In Python, the sys.stdin, sys.stdout, and sys.stderr are file-like objects that can
perform expected operations like read() and write()
STANDARD OUTPUT
import sys
print(type(sys.stdout))
sys.stdout.write('Hello\n')
STANDARD ERROR
Standard error works just like standard output and can be used the same way.
Standard error has file descriptor 2 where standard output has file descriptor 1. This
is beneficial if you want to separate warning and error messages from the actual
output of your application. For example, if your program outputs an XML file, you
don't want error strings injected in the middle of your XML file.
print(type(sys.stderr))
To pipe standard error from the shell to a file while leaving standard output going to
the terminal.
Page 20 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
print(type(sys.stdin))
print(letter)
If you want interactive input from the user, it is better to use input() instead of
sys.stdin.read() when asking for user input
Page 21 of 22
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
To read or write at a specific position, use the seek() function to set the current
read/write position.
Assuming that myfile.txt contains " Python is a widely used general-purpose" text,
the following example demonstrates the seek() method.
The output of the above example is " is a widely used general-purpose ".
Page 22 of 22