0% found this document useful (0 votes)
4 views17 pages

Module 5(Python)

This document provides an overview of Regular Expressions (RegEx) in Python, detailing how to use the 're' module for searching text patterns and handling file operations such as reading, writing, and appending files. It explains various methods for file handling, including creating, reading, and closing files, as well as counting lines in a text file. The document includes code examples to illustrate the concepts discussed.

Uploaded by

radharamyajena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Module 5(Python)

This document provides an overview of Regular Expressions (RegEx) in Python, detailing how to use the 're' module for searching text patterns and handling file operations such as reading, writing, and appending files. It explains various methods for file handling, including creating, reading, and closing files, as well as counting lines in a text file. The document includes code examples to illustrate the concepts discussed.

Uploaded by

radharamyajena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

MODULE-5

Regular Expression (RegEx) in Python with Examples

A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a
string or set of strings.

It can detect the presence or absence of a text by matching it with a particular pattern and also can
split a pattern into one or more sub-patterns.

The Python standard library provides a re module for regular expressions. Its primary function is to
offer a search, where it takes a regular expression and a string. Here, it either returns the first match
or else none.

• Python3

import re

match = re.search(r'portal', 'GeeksforGeeks: A computer science \

portal for geeks')

print(match)

print(match.group())

print('Start Index:', match.start())

print('End Index:', match.end())

Output

<_sre.SRE_Match object; span=(52, 58), match='portal'>

portal

Start Index: 52

End Index: 58

Here r character (r’portal’) stands for raw, not RegEx. The raw string is slightly different from a regular
string, it won’t interpret the \ character as an escape character. This is because the regular
expression engine uses \ character for its own escaping purpose.

Regex Module in Python

Python has a built-in module named “re” that is used for regular expressions in Python. We can
import this module by using the import statement.

Example: Importing re module in Python


Python

# importing re module

import re

How to Use RegEx in Python?

You can use RegEx in Python after importing re module.

Example:

This Python code uses regular expressions to search for the word “portal” in the given string and
then prints the start and end indices of the matched word within the string.

Python

import re

s = 'GeeksforGeeks: A computer science portal for geeks'

match = re.search(r'portal', s)

print('Start Index:', match.start())

print('End Index:', match.end())

Output

Start Index: 34

End Index: 40
Python File Handling
Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.

Python treats files differently as text or binary and this is important. Each line of code includes a
sequence of characters, and they form a text file. Each line of a file is terminated with a special
character, called the EOL or End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun. Let’s start with the reading and writing
files.

How to Create Files in Python


In Python, you use the open() function with one of the following options – "x" or "w" – to create a
new file:

"x" – Create: this command will create a new file if and only if there is no file already in existence
with that name or else it will return an error.

Example of creating a file in Python using the "x" command:

#creating a text file with the command function "x"

f = open("myfile.txt", "x")

We've now created a new empty text file! But if you retry the code above – for example, if you try to
create a new file with the same name as you used above (if you want to reuse the filename above)
you will get an error notifying you that the file already exists.

"w" – Write: this command will create a new text file whether or not there is a file in the memory
with the new specified name. It does not return an error if it finds an existing file with the same
name – instead it will overwrite the existing file.

Example of how to create a file with the "w" command:

#creating a text file with the command function "w"

f = open("myfile.txt", "w")

#This "w" command can also be used create a new file but unlike the the "x" command the "w"
command will overwrite any existing file found with the same file name.
With the code above, whether the file exists or the file doesn't exist in the memory, you can still go
ahead and use that code. Just keep in mind that it will overwrite the file if it finds an existing file with
the same name.

How to Write to a File in Python


There are two methods of writing to a file in Python, which are:

The write() method:

This function inserts the string into the text file on a single line.

Based on the file we have created above, the below line of code will insert the string into the created
text file, which is "myfile.txt.”

file.write("Hello There\n")

The writelines() method:

This function inserts multiple strings at the same time. A list of string elements is created, and each
string is then added to the text file.

Using the previously created file above, the below line of code will insert the string into the created
text file, which is "myfile.txt.”

f.writelines(["Hello World ", "You are welcome to Fcc\n"])

Example:

#This program shows how to write data in a text file.

file = open("myfile.txt","w")

L = ["This is Lagos \n","This is Python \n","This is Fcc \n"]

# i assigned ["This is Lagos \n","This is Python \n","This is Fcc \n"] to #variable L, you can use any
letter or word of your choice.

# Variable are containers in which values can be stored.


# The \n is placed to indicate the end of the line.

file.write("Hello There \n")

file.writelines(L)

file.close()

# Use the close() to change file access modes

How to Read From a Text File in Python

There are three methods of reading data from a text file in Python. They are:

The read() method:

This function returns the bytes read as a string. If no n is specified, it then reads the entire file.

Example:

f = open("myfiles.txt", "r")

#('r’) opens the text files for reading only

print(f.read())

#The "f.read" prints out the data in the text file in the shell when run.

The readline() method:

This function reads a line from a file and returns it as a string. It reads at most n bytes for the
specified n. But even if n is greater than the length of the line, it does not read more than one line.

f = open("myfiles.txt", "r")

print(f.readline())

The readlines() method:

This function reads all of the lines and returns them as string elements in a list, one for each line.

You can read the first two lines by calling readline() twice, reading the first two lines of the file:

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

print(f.readline())

How to Close a Text File in Python


It is good practice to always close the file when you are done with it.

Example of closing a text file:

This function closes the text file when you are done modifying it:

f = open("myfiles.txt", "r")

print(f.readline())

f.close()

The close() function at the end of the code tells Python that well, I am done with this section of
either creating or reading – it is just like saying End.

Example:

The program below shows more examples of ways to read and write data in a text file. Each line of
code has comments to help you understand what's going on:

# Program to show various ways to read and

# write data in a text file.

file = open("myfile.txt","w")

L = ["This is Lagos \n","This is Python \n","This is Fcc \n"]

#i assigned ["This is Lagos \n","This is Python \n","This is Fcc \n"]

#to variable L

#The \n is placed to indicate End of Line

file.write("Hello There \n")

file.writelines(L)
file.close()

# use the close() to change file access modes

file = open("myfile.txt","r+")

print("Output of the Read function is ")

print(file.read())

print()

# The seek(n) takes the file handle to the nth

# byte from the start.

file.seek(0)

print( "The output of the Readline function is ")

print(file.readline())

print()

file.seek(0)

# To show difference between read and readline

print("Output of Read(12) function is ")

print(file.read(12))

print()

file.seek(0)

print("Output of Readline(8) function is ")

print(file.readline(8))
file.seek(0)

# readlines function

print("Output of Readlines function is ")

print(file.readlines())

print()

file.close()

This is the output of the above code when run in the shell. I assigned "This is Lagos", "This is Python",
and "This is Fcc" to "L" and then asked it to print using the ''file.read'' function.

The code above shows that the "readline()" function is returning the letter based on the number
specified to it, while the "readlines()" function is returning every string assigned to "L" including the
\n. That is, the "readlines()" function will print out all data in the file.

Python File Open

Before performing any operation on the file like reading or writing, first, we have to open that file.
For this, we should use Python’s inbuilt function open() but at the time of opening, we have to
specify the mode, which represents the purpose of the opening file.

f = open(filename, mode)

Where the following mode is supported:

1. r: open an existing file for a read operation.

2. w: open an existing file for a write operation. If the file already contains some data, then it
will be overridden but if the file is not present then it creates the file as well.

3. a: open an existing file for append operation. It won’t override existing data.

4. r+: To read and write data into the file. This mode does not override the existing data, but
you can modify the data starting from the beginning of the file.

5. w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file
to zero length or create a file if it does not exist.

6. a+: To append and read data from the file. It won’t override existing data.

Working of Append Mode

Let us see how the append mode works.

Example: For this example, we will use the Python file created in the previous example.

Python

# Python code to illustrate append() mode


2

file = open('geek.txt', 'a')

file.write("This will add this line")

file.close()

Output:

This is the write commandIt allows us to write in a particular fileThis will add this line

There are also various other commands in Python file handling that are used to handle various tasks:

rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.

It is designed to provide much cleaner syntax and exception handling when you are working with
code. That explains why it’s good practice to use them with a statement where applicable. This is
helpful because using this method any files opened will be closed automatically after one is done, so
auto-cleanup.

Implementing all the functions in File Handling

In this example, we will cover all the concepts that we have seen above. Other than those, we will
also see how we can delete a file using the remove() function from Python os module .

Python

import os

def create_file(filename):

try:

with open(filename, 'w') as f:

f.write('Hello, world!\n')

print("File " + filename + " created successfully.")


8

except IOError:

print("Error: could not create file " + filename)

10

11

def read_file(filename):

12

try:

13

with open(filename, 'r') as f:

14

contents = f.read()

15

print(contents)

16

except IOError:

17

print("Error: could not read file " + filename)

18

19

def append_file(filename, text):

20

try:

21

with open(filename, 'a') as f:

22

f.write(text)

23
print("Text appended to file " + filename + " successfully.")

24

except IOError:

25

print("Error: could not append to file " + filename)

26

27

def rename_file(filename, new_filename):

28

try:

29

os.rename(filename, new_filename)

30

print("File " + filename + " renamed to " + new_filename + " successfully.")

31

except IOError:

32

print("Error: could not rename file " + filename)

33

34

def delete_file(filename):

35

try:

36

os.remove(filename)

37

print("File " + filename + " deleted successfully.")

38

except IOError:
39

print("Error: could not delete file " + filename)

40

41

42

if __name__ == '__main__':

43

filename = "example.txt"

44

new_filename = "new_example.txt"

45

46

create_file(filename)

47

read_file(filename)

48

append_file(filename, "This is some additional text.\n")

49

read_file(filename)

50

rename_file(filename, new_filename)

51

read_file(new_filename)

52

delete_file(new_filename)

Output:

File example.txt created successfully.


Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

Python File seek() Method


Example

Change the current file position to 4, and return the rest of the line:

f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())

Definition and Usage

The seek() method sets the current file position in a file stream.

The seek() method also returns the new postion.

Syntax

file.seek(offset)

Parameter Values

Parameter Description

Offset Required. A number representing the position to set the current file stream position.

More examples

Example

Return the new position:

f = open("demofile.txt", "r")
print(f.seek(4))

Python File tell() Method


Example

Find the current file position:


f = open("demofile.txt", "r")
print(f.tell())

Definition and Usage

The tell() method returns the current file position in a file stream.

Tip: You can change the current file position with the seek() method.

Syntax

file.tell()

Parameter Values

No parameter values.

Example

Return the current file position after reading the first line:

f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())

Count number of lines in a text file in Python


Counting the number of characters is important because almost all the text boxes that rely on user
input have a certain limit on the number of characters that can be inserted. For example, If the file is
small, you can use readlines() or a loop approach in Python.

Input: line 1

line 2

line 3

Output: 3

Explanation: The Input has 3 number of line in it so we get 3 as our output.

Count the Number of Lines in a Text File

Below are the methods that we will cover in this article:

• Using readlines()

• Using enumerate

• Use Loop and Counter to Count Lines

• Use the Loop and Sum functions to Count Lines

Below is the implementation.

Let’s suppose the text file looks like this


myfile.txt

Python counts the number of lines in a string using readlines()

The readlines() are used to read all the lines in a single go and then return them as each line is a
string element in a list. This function can be used for small files.

• Python3

with open(r"myfile.txt", 'r') as fp:

lines = len(fp.readlines())

print('Total Number of lines:', lines)

Output:

Total Number of lines: 5

Python counts the number of lines in a text file using enumerate

Enumerate() method adds a counter to an iterable and returns it in the form of an enumerating
object.

• Python3

with open(r"myfile.txt", 'r') as fp:

for count, line in enumerate(fp):

pass

print('Total Number of lines:', count + 1)

Output:

Total Number of lines: 5


Use Loop and Counter to Count Lines in Python

Loops Python is used for sequential traversal. here we will count the number of lines using the loop
and if statement. if help us to determine if is there any character or not, if there will be any character
present the IF condition returns true and the counter will increment.

• Python3

file = open("gfg.txt", "r")

Counter = 0

# Reading from file

Content = file.read()

CoList = Content.split("\n")

for i in CoList:

if i:

Counter += 1

print("This is the number of lines in the file")

print(Counter)

Output:

This is the number of lines in the file

Use the Loop and Sum functions to Count Lines in Python

Loops Python is used for sequential traversal. here we will count the number of lines using the sum
function in Python. if help us to determine if is there any character or not, if there will be any
character present the IF condition returns true and the counter will increment.

• Python3

with open(r"myfile.txt", 'r') as fp:

lines = sum(1 for line in fp)

print('Total Number of lines:', lines)

Output:Total Number of lines: 5

You might also like