Python  

Python - File Operations and Regular Expressions

In the last session, we discussed the file path methods and Regular Expressions. Now, we will look at Python's File operations.

Let’s start,

File handling is a crucial part of any programming language. Python provides built-in functions and methods to read from and write to files, both text and binary. This lesson will cover the basics of file handling, including reading and writing text files and binary files.

  1. Read a Whole File using python

#Input
#Need to create a "example.txt" file and enter "welcome" 
with open('example.txt','r') as file:
    content=file.read()
    print(content)

#Output
Welcome
  1. Read a file line by line in python

#Input
with open('example.txt','r') as file:
    for line in file:
        print(line.strip()) ## sstrip() removes the newline character

#Output
welcome to python
hello
  1. Writing a file(Overwriting) in python

#Input
with open('example.txt','w') as file:
    file.write('Hello World!\n')
    file.write('this is a new line.')
    print(file)

#Output
Hello World!
this is a new line.
  1. Write a file(without Overwriting) in python

#Input
with open('example.txt','a') as file:
    file.write("Append operation taking place!\n")

#Output
Hello World!
this is a new line.
Append operation taking place!
  1. Writing a list of lines to a file in python

#Input
lines=['First line \n','Second line \n','Third line\n']
with open('example.txt','a') as file:
    file.writelines(lines)

#Output
Hello World!
this is a new line.Append operation taking place!
First line 
Second line 
Third line
  1. Read the content from source text file and write to a destination text file using python

#Input
with open('example.txt', 'r') as source_file:
    content = source_file.read()

with open('destination.txt', 'w') as destination_file:
    destination_file.write(content)


#Output
#destination.txt file created and write the below content
Hello World!
this is a new line.Append operation taking place!
First line 
Second line 
Third line
  1. The w+ mode in Python is used to open a file for both reading and writing. If the file does not exist, it will be created. If the file exists, its content is truncated (now the file is overwritten)

#Input
with open('example.txt','w+') as file:
    file.write("Hello world\n")
    file.write("This is a new line \n")

    ## Move the file cursor to the beginning
    file.seek(0)

    ## Read the content of the file
    content=file.read()
    print(content)

#Output
Hello world
This is a new line 
  1. Read a text file and count the number of lines, words, and characters.

#Input
def count_text_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        line_count = len(lines)
        word_count = sum(len(line.split()) for line in lines)
        char_count = sum(len(line) for line in lines)
    return line_count, word_count, char_count

file_path = 'example.txt'
lines, words, characters = count_text_file(file_path)
print(f'Lines: {lines}, Words: {words}, Characters: {characters}')

#Output
Lines: 5, Words: 16, Characters: 99
  1. Regular Expressions: Find All Numbers using Regular Expression

#Input
import re

text = "My age is 25 and my brother is 18"
result = re.findall(r"\d+", text)
print(result)

#Output
['25', '18']
  1. Check if the String is a Valid Email using Regular Expression

#Input
import re

email = "[email protected]"
pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"

if re.match(pattern, email):
    print("Valid email")
else:
    print("Invalid email")

#Output
Valid email
  1. Extract Only Letters using Regular Expression

#Input
import re

text = "Hello123World"
result = re.findall(r"[A-Za-z]+", text)
print(result)

#Output
['Hello', 'World']

Now, We have covered file operations and Regular Expression with various examples. In the next article, we will dive into NumPy operations in Python.