|

Python Text File Handling Notes – Class 12 CS (083)

Python Text File Handling Notes for Class 12 covers file opening, closing, with clause, write(), writelines(), read(), readline(), readlines(), seek(), tell().

Text File is an important part of the File Handling in Python chapter for Class 12 Computer Science (083). These notes have been carefully curated by subject matter experts, covering all important concepts and exam-relevant topics. The content is presented in a simple, student-friendly manner to help learners understand each concept with ease, build strong fundamentals, and approach examinations with greater confidence.

Text File

  • A text file is a sequence of characters including alphabets, numbers, and special symbols.
  • Common examples of text files include files with extensions like .txt, .py, .csv, etc.
  • When opened in a text editor (like Notepad), the content appears as readable text in multiple lines.
  • Internally, the file is not stored as characters but as a sequence of bytes (0s and 1s).
  • While opening the file, the text editor converts these byte values into human-readable characters.
  • Each line in a text file ends with a special character called End of Line (EOL).
  • In Python, the default EOL character is newline (\n).
  • Data in a text file is usually separated by whitespace, but comma ( , ) and tab (\t) are also commonly used.

Text files contain only the ASCII equivalent of the contents of the file whereas a .docx file contains many additional information like the author’s name, page settings, font type and size, date of creation and modification, etc.

Opening and Closing a Text File

Opening a File

  • A file is opened in Python using the open() function.
  • Syntax:
    file_object = open(file_name, access_mode)
  • The open() function:
    • Returns a file object (file handle)
    • This object is used to perform read/write operations
  • If the file does not exist a new empty file is created with the given name
  • The file_object establishes a link between the program and the data file stored in the permanent storage
  • File Object has certain Attributes:
    • file.closed → Returns True if file is closed, otherwise False
    • file.mode → Returns the mode in which file was opened
    • file.name → Returns the name of the file
  • If the file is not in the current directory, full path must be provided along with the file name
  • Access Mode
    • It is an optional argument that specifies how the file will be used.
    • It defines the operation to be performed on the file.
    • Default mode is read (r).
    • Common modes include: r → Read, w → Write, + → Read and write, a → Append (add data at the end)
  • Files can be opened in:
    • Text mode (default) → data is read/written as strings
    • Binary mode (b) → data is read/written as bytes
  • Non-text files are handled in binary mode.
  • Different file modes also determine the file offset position, i.e., the position of the file pointer when the file is opened.

File Open Mode

File ModeDescriptionFile Offset Position
rOpens the file in read-only mode.Beginning of the file
rbOpens the file in binary read-only mode.Beginning of the file
r+ or +rOpens the file in both read and write mode.Beginning of the file
wOpens the file in write mode. Overwrites content if file exists, otherwise creates a new file.Beginning of the file
wb+ or +wbOpens the file in read, write, and binary mode. Overwrites if exists, otherwise creates a new file.Beginning of the file
aOpens the file in append mode. Creates a new file if it does not exist.End of the file
a+ or +aOpens the file in append and read mode. Creates a new file if it does not exist.End of the file

Closing a File

  • After completing read/write operations, it is a good practice to close the file.
  • Python provides the close() method for this purpose.
  • Syntax:
    file_object.close()
  • file_object is the object returned when the file was opened.
  • When a file is closed: the system frees the memory allocated to it
  • Python ensures that: any unwritten or unsaved data is written to the file before closing
  • It is always recommended to close the file after use.
  • If a file object is reassigned to another file, the previous file is automatically closed

Opening a File using ‘with’ Clause

  • A file can also be opened using the with clause.
  • Syntax:
    with open(file_name, access_mode) as file_object:

Writing to a Text File

  • To write data, the file must be opened in write (w) or append (a) mode.
  • In write mode:
    • Existing content is erased
    • File pointer is at the beginning
  • In append mode:
    • New data is added at the end
    • File pointer is at the end
  • Methods used for writing:
    • write() → writes a single string
    • writelines() → writes multiple strings

write() Method

  • write() takes a string and writes it to the file.
  • It returns the number of characters written.
  • Newline (\n) must be added manually for new lines.
  • Numeric data must be converted to string before writing.
  • Data is first written to a buffer and saved to file on closing.
  • flush() can be used to force writing buffer content to file.

Example: write()

myobject = open(“myfile.txt”, ‘w’)
myobject.write(“Hey I have started using files in Python\n”)
myobject.close()

writelines() Method

  • Used to write multiple strings at once.
  • Takes an iterable like list or tuple of strings.
  • Does not return number of characters written.

Example: writelines()

myobject = open(“myfile.txt”, ‘w’)
lines = [“Hello everyone\n”, “Writing multiline strings\n”, “This is the third line”]
myobject.writelines(lines)
myobject.close()

Reading from a Text File

  • File must be opened in modes like r, r+, w+, a+ before reading.
  • There are three methods to read file content:
    • read()
    • readline()
    • readlines()

read() Method

  • Reads specified number of characters/bytes.
  • If no argument is given, reads entire file.

myobject = open(“myfile.txt”, ‘r’)
print(myobject.read(10))
myobject.close()

readline() Method

  • Reads one complete line at a time.
  • Can read limited characters but only up to newline (\n).
  • Returns empty string at end of file.
  • Can be used with loop to read file line by line.

myobject = open(“myfile.txt”, ‘r’)
print(myobject.readline())
myobject.close()

readlines() Method

  • Reads all lines and returns them as a list.
  • Each line ends with \n.

Program: Write and Read File

fobject = open(“testfile.txt”, “w”)
sentence = input(“Enter the contents to be written in the file: “)
fobject.write(sentence)
fobject.close()

print(“Now reading the contents of the file:”)
fobject = open(“testfile.txt”, “r”)
for line in fobject:
    print(line)
fobject.close()

Setting Offsets in a File

  • By default, file data is accessed sequentially, but for random access Python provides seek() and tell() methods.

tell() method:

  • Returns the current position of the file object
  • Position is measured in bytes from the beginning of the file

seek() method:

  • Used to move the file object to a specific position
  • Syntax: file_object.seek(offset [, reference_point])
  • offset → number of bytes to move
  • reference_point can be:
    • 0 → beginning of file
    • 1 → current position
    • 2 → end of file
  • Default reference point is 0

Example: seek() and tell()

print(“Learning to move the file object”)
fileobject = open(“testfile.txt”, “r+”)
str = fileobject.read()
print(str)
print(“Initially, the position of the file object is:”, fileobject.tell())
fileobject.seek(0)
print(“Now the file object is at the beginning of the file:”, fileobject.tell())
fileobject.seek(10)
print(“The position of the file object is at”, fileobject.tell())
str = fileobject.read()
print(str)

Creating, Writing and Reading a Text File

fileobject = open(“practice.txt”, “w+”)
while True:
    data = input(“Enter data to save in the text file: “)
    fileobject.write(data)
    ans = input(“Do you wish to enter more data?(y/n): “)
    if ans == ‘n’:
        break
fileobject.close()

fileobject = open(“practice.txt”, “r”)
str = fileobject.readline()
while str:
    print(str)
    str = fileobject.readline()
fileobject.close()

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *