Python Text Processing Useful Resources

Python Text Processing - File as String



While reading a file it is read as a dictionary with multiple elements. So, we can access each line of the file using the index of the element. In the below example we have a file which has multiple lines and they those lines become individual elements of the file.

Example - Reading a File line by line

main.py

with open ("GodFather.txt", "r") as BigFile:
    data=BigFile.readlines()

# Print each line
	for i in range(len(data)):
    print("Line No -",i)
    print(data[i])

When we run the above program, we get the following output −

Line No - 0
Vito Corleone is the aging don (head) of the Corleone Mafia Family. 
...

File as a String

But the entire file content can be read as a single string by removing the new line character and using the read function as shown below. In the result there are no multiple lines.

main.py

with open("GodFather.txt", 'r') as BigFile:
    data=BigFile.read().replace('\n', '')
	
# Verify the string type 
	print(type(data))
	
# Print the file content as a single string
    print(data)

Output

When we run the above program, we get the following output −

string
Vito Corleone is the aging don (head) of the Corleone Mafia Family...
Advertisements