Python For System Admin Fast BootCamp. Modifying file read and write and using regular expression.

In this tutorial fast boot camp for python for system admin , we will look into how to open , edit file and use regular expression for quickly replace text . useful for system admin.

File Modes in Python

ModeDescription
‘r’This is the default mode. It Opens file for reading.
‘w’This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
‘x’Creates a new file. If file already exists, the operation fails.
‘a’Open file in append mode.
If file does not exist, it creates a new file.
‘t’This is the default mode. It opens in text mode.
‘b’This opens in binary mode.
‘+’This will open a file for reading and writing (updating)

example of code how to open file in python.

  • File open to write :
# we are trying to write test.txt with some line .
file = open ("test.txt" , "w")
for i in range (10):
    file.write("Print this line number = %d n" % (i+1))
file.close()
  • File open to read
# Lets try to open file test.txt that we previously wrote
file = open("test.txt" , "r")
for i in file.readlines():
    print (i)
file.close()
 Print this line number = 1
 Print this line number = 2
 Print this line number = 3
 Print this line number = 4
 Print this line number = 5
 Print this line number = 6
 Print this line number = 7
 Print this line number = 8
 Print this line number = 9
 Print this line number = 10 

Python Regular Expression Tutorial

Please see this link for quick reference of regular expression. https://dodocrypto.com/index.php/2019/11/12/regular-expression-cheat-sheet-for-dummies/

List of Python re module .

The re module offers a set of functions that allows us to search a string for a match:

FunctionDescription
findallReturns a list containing all matches
searchReturns a Match object if there is a match anywhere in the string
splitReturns a list where the string has been split at each match
subReplaces one or many matches with a string

Let’s start with findall() . The findall() function returns a list containing all matches. Note : We will be using test.txt from example that we made earlier.

import re;
file = open ("test.txt" , "r" )
for i in file.readlines():
    result = re.findall (r"d+" , i)
    print (result)
file.close()
----------------------------------------------------------------
this will print out the number 1 to 10 and d+ mean match any digit or numeric at least one or more

The search() Function

The search() function searches the string for a match, and returns a Match object if there is a match.If there is more than one match, only the first occurrence of the match will be returned:

import re
file = open ("test.txt", "r")
for i in file.readlines():
    result = re.search (r"d+" , i)
    print (result.group())
file.close()
-----------------------------------
This will print 1 - 10

The split() Function

The split() function returns a list where the string has been split at each match:

import re
file = open ("test.txt" , "r")
for i in file.readlines():
    result = re.split (r"s", i)
    print (result)
file.close()
------------------- this will return
['Print', 'this', 'line', 'number', '=', '1', '', '']
 ['Print', 'this', 'line', 'number', '=', '2', '', '']
 ['Print', 'this', 'line', 'number', '=', '3', '', '']
 ['Print', 'this', 'line', 'number', '=', '4', '', '']
 ['Print', 'this', 'line', 'number', '=', '5', '', '']
 ['Print', 'this', 'line', 'number', '=', '6', '', '']
 ['Print', 'this', 'line', 'number', '=', '7', '', '']
 ['Print', 'this', 'line', 'number', '=', '8', '', '']
 ['Print', 'this', 'line', 'number', '=', '9', '', '']
 ['Print', 'this', 'line', 'number', '=', '10', '', '']

The sub() Function

The sub() function replaces the matches with the text of your choice:

import re
file = open ("test.txt" , "r")
result = file.read()
filew = open ("test.txt" , "w")
## We replace Print in test.txt to be New Print
result = re.sub(r"Print" , "New Print" , result)
## We replace number to blank
result = re.sub(r"d+" , "" , result)
## We replace number to Number
result = re.sub(r"number", "Number" , result )
filew.write(result)
filew.close()
file.close()
 ================
this will result in file text
New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =
 New Print this line Number =

Remember to use readlines() in a big file instead of read()

Check out next tutorial at :

One Reply to “Python For System Admin Fast BootCamp. Modifying file read and write and using regular expression.”

Leave a Reply

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