Working with Text Files

 

# Text File

  • Definition: A text file is a sequence of characters containing alphabets, numbers, and special symbols.
  • Examples: Files with extensions like .txt, .py, .csv, etc. are considered as text files.
  • Storage: Internally, text file contents are stored as a sequence of bytes consisting of 0s and 1s, using encoding schemes such as ASCII, UNICODE, or others.
  • Text Editors: When opened in a text editor, the ASCII values are translated to display readable characters for humans.
  • End of Line (EOL): Each line of a text file is terminated by a special character, such as the newline (\n) in Python. Other characters can also be used to indicate EOL.
  • Separators: Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also commonly used to separate values.


# Text file access mode

In Python, you can use various file access modes to interact with text files. Here are the different text file access modes:

  • 'r': Open for reading (default). If the file does not exist, it raises a FileNotFoundError.
  • 'w': Open for writing. It truncates the file to zero length if it exists, or creates a new file if it does not exist.
  • 'a': Open for writing. It appends data to the end of the file. The file is created if it does not exist.
  • 'r+': Open for reading and writing.
  • 'w+': Open for writing and reading. It truncates the file to zero length if it exists, or creates a new file if it does not exist.
  • 'a+': Open for reading and writing. It appends data to the end of the file. The file is created if it does not exist.


# File Object Attributes

  • 'file.closed' : Returns 'True' if the the file is closed, otherwise 'False'.
  • 'file.mode' : Returns the access mode in which file was opened.
  • 'file.name' : Returns the name of the file.


# Creating a Text File

Code :

f=open("TextFile.txt","w")
print("The name of the file is",f.name)
print("Closed or not :",f.closed)
print("Opening mode :",f.mode)

Output :

The name of the file is TextFile.txt

Closed or not : False

Opening mode : w


# Closing a File

We use the close() function.

f=open("TextFile.txt","w")
print("The name of the file is",f.name)
print("Closed or not :",f.closed)
print("Opening mode :",f.mode)
f.close

NOTE : No special message occurs when a file is closed.


# NOTE

We will use the sample text as follows :

Hello there.

My name is Aditya Kumkar.

I am going to be an excellent engineer, a master problem solver and a learner for life.


# Writing into Files

(a) write() function

Theory :

write() method takes a string and writes it into the file. This method does not add a new line character ('\n') to the end of the string.


Code :

f=open("TextFile.txt","a+")
content=input("Enter the content here :")
f.write(content)
print("The file reads as : ",content)


Output :

Enter the content here : Hello there. My name is Aditya Kumkar.
The file reads as : Hello there. My name is Aditya Kumkar.

(b) writelines() function

Theory :

Whenever we have to write a sequence of string to a file, we will use writelines() instead of write().

Code :

a=input("Enter line 1 : ")
b=input("Enter line 2 : ")
c=input("Enter line 3 : ")
lines = [a,b,c] # Using Lists
f=open("TextFile.txt", "w")
f.writelines(lines)
f=open("TextFile.txt", "r")
content = f.read()
print(content)

Output :

Enter line 1 : Hello there. 
Enter line 2 : My name is Aditya Kumkar.
Enter line 3 : I am going to be an excellent engineer, a master problem solver and a learner for life.
Hello there. My name is Aditya Kumkar.I am going to be an excellent engineer, a master problem solver and a learner for life.


# Reading from Files

Here, the content of file 'TextFile.txt' is as follows:

Hello there. My name is Aditya Kumkar. I am going to be an excellent engineer, a master problem solver and a learner for life.


(a) read() method

This method returns a string containing all characters in a file.


Code :

f=open("TextFile.txt", "r")
content = f.read()
print(content)

Output :

Hello there. My name is Aditya Kumkar. I am going to be an excellent engineer, a master problem solver and a learner for life.


(b) read([Size]) method

This method specifies how many characters the string should return.

Code :

f=open("TextFile.txt", "r")
content = f.read(20)
print(content)

Output :

Hello there. My name


(c) readline() method

the readline() method will read a file line by line. For readline(), a line is terminated by '\n' or End of Line (EOL) i.e. a new line character. When end of file is reached, readline() will return an empty string.


Code :

f=open("TextFile.txt", "r")
content = f.readline()
print(content)

Output :

Hello there. My name is Aditya Kumkar. I am going to be an excellent engineer, a master problem solver and a learner for life.


Difference between read() and readline()
read():
The read() method reads the entire file or a specified number of bytes from the file, depending on the argument provided.
If no argument is provided, it reads the entire file.
It returns a string containing the specified number of bytes or the entire file content.
readline():
The readline() method reads a single line from the file.
If the optional size argument is provided, it reads at most that many bytes. However, if the size argument is negative or omitted, it reads until the end of the line.
It returns the line as a string including the newline character at the end of the line.


(d) readlines() method

This method will return a list of strings, each separated by '\n'.

This method reads all rows and retains the newline character that is at the end of every row.


Code :

f=open("TextFile.txt", "r")
content = f.readlines()
print(content)

Output :

['Hello there. My name is Aditya Kumkar.I am going to be an excellent engineer, a master problem solver and a learner for life.']


# OS Module

The Python OS module enables interactions with the operating system. The OS module provides the function that are involved in the file processing operations like renaming, deleting, etc.


# Renaming and Deleting Files


(a) rename() method

This method is used to rename the file. This method does not return any value.


Code :

import os
f="TextFile.txt"
os.rename("TextFile.txt","Textfile.txt")
a="Textfile.txt"

c=open("Textfile.txt","r")
content=c.read()
print("The contents of new file are :\n",content)

Output :

The contents of new file are :
 Hello there. My name is Aditya Kumkar.I am going to be an excellent engineer, a master problem solver and a learner for life.

NOTE : No special message occurs when a file is renamed.


(b) remove() method

This method is used to remove the existing file. This method does not return any value.


Code :

import os
f="Textfile.txt"
os.remove(f)

NOTE : No special message occurs when a file is removed.


# Appending Data into a File

In order to append a new line in your existing file, you need to open the file in append mode, by setting 'a' as the mode.

With file access mode 'a', open() first checks if file exists or not. If the file does not exist, then creates an empty file and opens it. Whereas if file exists then opens it. You can also use file access mode 'a+' to open file in reading as well as writing mode.


Code :

f=open("TextFile.txt","a")
f.write("\n I am in Class 12.")
f=open("TextFile.txt","r")
content= f.read()
print(content)

Output :

Hello there. My name is Aditya Kumkar.I am going to be an excellent engineer, a master problem solver and a learner for life.
 I am in Class 12.

# Random Access Methods

The functions that we have learnt till now are used to access the data sequentially from a file. But if we want to access data in a random fashion, then Python gives us seek() and tell() functions to do so.


(a) tell() method

This method tells you the current position of the file object within the file, measured in bytes from the beginning of the file.


Code :

import os
f=open("Textfile.txt","r")
p = f.tell()
print("Current position is : ", p)

Output :

Current position is : 0

Alternate :

import os
f=open("Textfile.txt","a")
p = f.tell()
print("Current position is : ", p)

Output :

Current position is : 145


(b) seek() method

This method can be used to change the current position of a file object in a file. This method does not return any value.


Syntax :

FileObject.seek(offset[,mode])


Parameters :

  • offset This argument indicates the number of bytes to be moved.
  • mode This is a number 0 or 1 or 2 signifying. If mode is set to 0, it means use the beginning of the file as the reference position, 1 means use the current position and 2 means use end of file would be taken as reference point.

Code :

import os
f=open("Textfile.txt","r")
f.seek(50)
content =f.read()
print("The remaining content is : ", content)

Output :

The remaining content is : o be an excellent engineer, a master problem solver and a learner for life.
 I am in Class 12.


Popular posts from this blog