#

Monday, May 5, 2025

Opening & Closing a Text File

Following code is the classic way of opening and closing a text file.

1st line opens a file which is in the current directory and the other line closes the file.


Since the above way always needs the closing statement to close the file, the better Pythonic way of doing this is to use a context manager. A context manager is a construct that properly manages the setup and teardown of resources like files, network connections, or locks using the with statement.

This way, when you exit from the indentation, the file is closed automatically.



Above code opens the file and save it in the memory as "f" and reads it and stores it in the variable called "output" and prints it out. Basically it prints the text file contents to the CLI.

Following is the sample.txt file in the working directory and let's run the above to see the output.







Output will be:





If we want to get the lines into a List,





Output will be:



Writing to a Text File

Following syntax will write a text to a file.

"w" implies that the file is opened to write, default it read only.


But this actually overwrites the file, so following will be the contents inside the file.





Instead we can append the text we want by opening the file with "a" append mode.





Output will be:
By proper spacing, using \n for line breaking, we can form the text much better.



Following example shows how we can write a file with List of data using f.writelines() method.






Output will be like the following..





Following sample code open 2 files and file and copy the contents of the source file to the destination file after manipulating the text. This is the advantage of copying it to memory. This example capitalizes the letters in the text.






Output will be:






Note:- Even though we need a file with the specified name already to work with reading, that is not the case for writing, It creates a new file if it does not exist.

Note:- 
If we want to read or write a file in another directory, we should give the path like the following.





Since forward slash (/) is used in Linux and back slash (\) is used in Windows, writing scripts to match the host OS can be problematic, Because of this, following piece of code helps to build the directory path according to the OS.







Since my one is Linux, output is:

Sunday, May 4, 2025

There are many types of programming languages. As an example, there are Procedural programming languages like Pascal, C, etc while there are Declarative languages like SQL and there are Object Oriented languages like Java. Python is a type of Functional programming language which does support Object Oriented Programming.

Comprehensions

This means to a concise way to create collections like Lists, Dictionaries, or Sets using a single line of code. Following example will explain what it is practically.

Following code captures the Gig interfaces in the traditional way..










Following code will give the same output and it is more Pythonic..







Single line covers it, there are actually 3 sections, let's break it down.








If we read the sections like the way I have numbered above, it is more understandable.

Note:- If we want to get the output in some modified way, as an example in block letters, we can use int.upper() to replace just int which is the expression.

Following example shows how Comprehension works for a Dictionary which outputs the routers which are up.


Lambda Function

A Lambda function in Python is a small, anonymous function defined using the lambda keyword. It's often used for short, simple operations and also called throw away functions after use.

Following example shows a Lambda function which adds 2 given values in single line of code.





Following is another one which compares a given number with 5 to check greater than or lesser.





Map Function

The map() function in Python applies a function to every item of an iterable (like a List) and returns a map object (which you can convert to a list, tuple, etc.).

Syntax is like the following..
map(function, iterable)

Note:- x**2 is the way to get square, double multiply..




Output will be;




Filter Function

The filter() function in Python is used to filter elements of an iterable (like a List) based on a function that returns True or False.

Syntax is like the following..
filter(function, iterable)

Note:- % checks the remainder..




Output will be;



Reduce Function

The reduce() function in Python is used to apply a function cumulatively to the items of a sequence, reducing the sequence to a single value.

Syntax is like the following..
reduce(function, iterable)

What this gives is the multiplication of all the values together. 1x2 = 2 then 2x3 = 6 then 6x4 =24 and finally 24x5 = 120

Note:- reduce should be imported from functools library

Here is another example of reduce() function

Note:- " " in the Lamba function is to make the space and the result will be like the following..






Saturday, May 3, 2025

Modules are Python files which ends with .py and Packages are directories which includes a collection of one or more Modules with a __init__.py file. A Library on the other hand can be a single module, a package, or a collection of Packages and Modules.

Standard Library

Following is the link to get info about all the Modules in Standard library.


Following example show the syntax of importing "time" module from Standard library and doing a simple work..







3rd Party Libraries

Let's see an example of a 3rd party library called "rich", 1st it needs to be installed..

pip3 install rich



This code makes the print text red, that's one thing the rich library do, styling..



Output will be;
If you noticed, the file I created is saved in /home/roshan/Python-Net-Eng/.venv/lib/python3.8/site-packages since this is the folder which the rich library is downloaded and installed. This is because when it tries to import there are certain locations it looks in including the current working directory. If it could not find it in those locations, script is not compiled. 

Following script shows which locations it looks to import the modules.




Import only a Module from a Library

Above example of importing rich library actually imported whole library, but in case if you need only a specific module to be imported from a library, following is the syntax.






In this case, the rich.print() is not working, instead we can use directly print().
But if we need to use the default print() function along with it, we can use an alias to the imported function like the following example.







Output will be like the following..





Let's do something manually to understand how it's working by creating a custom module.
Let's say we have a Module named "Modules.py" which I created with the following code in it, 







Following is the syntax to import only a one function inside above module,


Functions in a programming language are defined to get rid of repeating set of codes in a script. Following link is the official place to find built in functions in python.


We can also use built in function help() to get the info about a specific function through CLI, just by sending the name of the function we need help with in the parenthesis.

Basics of Defining and Calling Functions 

Following is the basic syntax to define a custom / user defined function in Python.






It can be called just by the name followed by parenthesis at anywhere in the code.
If passing variables to a function while calling it is necessary, following is the way to define it and call it.

Note:- "a" and "b" are parameters and "5" and "3" are called arguments.





The result will be;




Another example to push string arguments will be;









The result will be,




You can also notice that there is a doc string within triple quotation marks """XYZ""" which is the comment which help someone to understand the code and this is the text which optouts if someone send this function through the help function means if someone calls it by help(customf), following will be the result;







Note:- Some people prefer to view the doc string by the following way,

This is basically the same information as help funtion.


Following syntax specifies how we can define a default argument value in a function, which comes to play like in the following examples.










The result will automatically add "gmail.com" as the 2nd argument.




Following syntax shows how you can mix the order of sending arguments to a function called "keyword arguments", basically the Positional Arguments can not come after Keyword Arguments. "user" is a positional argument and domain is a keyword argument here.









Result will be,



You can send multiple arguments in a list to a function like the following.

Here the "num_list" parameter takes in the argument as a list and sum up all together, no matter how many items are in the list.






The above can be scripted in the following way also,

By this method, we don't want to send the argument as a List as the parameter is coded to take any amount of arguments. They are called star args (unpacking operator *) in python.

This can't be used with keyword arguments just like the above way but you can do something like the following if you use ** double stars.








This takes the passed arguments as a dictionary (key value pairs) and unpacking with iterating using for loop to make the following output.





We can send any amount of kwargs (keyword arguments) as you want like this.

We can also combine above different methods of sending arguments but have to use the following order.




Returning values from a Function

This is where the values which comes as a result of running a function can be used for some other thing later in a code. By default, a function returns none, but if we assigned the result to a variable, we can use it later like the following,











In the above example, "return email" means returning the final output of the function which is assigned to a variable called "email" is returned back to where the function is called and it is stored in the variable called "my_email".

So the result will be;




Note that you cannot call the variable "email" outside the function as it is cleared after running the function once.

Following example shows how to return multiple values from a funtion.











Scopes of Variables

In Python, there are 4 Scopes.

1. Built-in
2. Global
3. Local
4. Enclosing

Built-in variables are predefined keyword kind of variables which can be accessed from anywhere.
Global Scope is defined outside of any function so that it can be accessed from anywhere in the code.
Local is defined inside a function and can only be accessed within that function.
Enclosing is defined at parent functions which can be accessed by the child functions (functions within functions)

"gname" is a globally defined variable, "ename" is a enclosed variable and a local variable to function named brand() and "lname" is a locally defined variable inside the function nbrand() and nbrand() is a function inside brand().

If this script is run, the output will be like the following..

cisco
meraki
huawei
cisco