Saturday, September 30, 2023

python module commands

#### To get module help information details :- help(module)

example : - help(os) 

 os.get_exec_path()

os.getenv('ORACLE_HOME')

os.environ.get('ORACLE_HOME')

To set environ 

os.environ['ORACLE_HOME'] = '/u02/app/oracle/product/19c'

os.uname()

os.path.getmtime(path) ---> get modified time

import os, sys, time 

local_time = time.ctime(os.path.getmtime(path))  # get time in local format 

os.path.size(path/(1024*1024*1024)) # get size in GB default bytes 

os.path.isabs(path) # check if path is absolute boolean

os.path.isfile(path) # check if path is file boolean

os.path.isdir(path) # check if path is directory boolean

os.path.islink(path) # check if file is link boolean

os.path.ismount(path) # check if the block device is mounted or not boolean

os.path.samefile(path1,path2) # check if the files are same boolean

os.symlink(source,destination) # create soft link

os.link(source,destination) # create hard link

os.access(path,os.F_OK) #check files exists boolean

os.access(path,os.R_OK) # check file is readable boolean

os.access(path,os.W_OK) # check file is writable boolean

os.access(path,os.X_OK) # check file is executable boolean

print(os.path.abspath(__file__)) # show the self script name 


SYS 

import sys

command_line_user_input = sys.stdin.readline()  # it will wait for your terminal input will record it

print(command_line_user_input)

# writing to stdout

sys.stdout.write("This is stdout. \n")

# writing to stderr

sys.stderr.write("This is stderr. \n")

# sys exit

sys.exit(1)

# linux/windows info 

print(sys.platform)

# linux version 

print(sys.version)

# modules 

for module in sys.modules:

    print(module)

# to execute os commands 

os.system("command")

# to create directory

os.mkdir(path)

# to get current working directory

os.getcwd()

# to change directory

os.chdir(path)

# to change join path

os.path.join(path,new_file)

# to truncate file size in bytes 

os.truncate(path,length) # length = 1024*1024*1024 ~ 1GB

# to get basename 

os.path.basename(path)  # will return only file/dir name 

# to get relative path

os.path.relpath(path)

# to get absolute path

os.path.abspath(path)

# check if file dir exists or not boolean

os.path.exists(path) 

# to create directory 

os.mkdir(path)

# to delete directory

os.rmdir(path)

# to delete file 

os.remove(path)

# Using a with statement to open and automatically close the file 👉

Opening a File:-
To open a file, you can use the open() function with the desired file name and mode. The common modes are:
'r': Read (default mode).
'w': Write (creates a new file or truncates an existing file).
'a': Append (opens a file for writing in append mode, creating a new file if it doesn't exist).
'x': Exclusive creation (creates a new file but raises an error if it already exists).
'b': Binary mode (e.g., 'rb' for reading a binary file).

with open('example.txt', 'w') as file:
...     file.write("hello")
...     file.write("this is second line.\n")
...     file.write("this is third line. \n")

# without using with open :-
>>> file = open('example.txt', 'w')
>>> file.write("Hello, world! \n")
15
>>> file.write("second line.\n")
13
>>> file.write("third line.\n")
12
>>> file.close()

# to read lines from above file  👉
with open('example.txt', 'r') as file:
...    lines = file.readlines()
...    for line in lines :
...          print(line.strip())

# to read lines using 👉
with open('example.txt', 'r') as file :
...     lines = [line.strip() for line in file]
...     for line in lines:
...             print(line)

# to read line simply 👉 
with open('example.txt', 'r') as file:
...     for line in file:
...             print(line.strip())

Operators in Python

 operators :-

Arithmetic Operators:-  +,-,/,*,%,//,**

Comparison Operators :- <,>,>=,<=,!=,==

Logical Operators :- and, or, not

Bitwise Operators:- 

Assignment Operators:- *=,-=,+=,/=,//=,**=,

Identity Operators:- is, is not 

Membership Operators :- in , not in 


identity operators:-

a=10

b=20

print(a is b)  # false

print(a is not b)  #true 


membership operators :-

a = [1,2,3,4,5]

b=2

c=12

print(b in a)  # true

print(c not in a)  # true 

Friday, September 29, 2023

Generics in Python "Annotation Variables and Functions"

 def add(x: int, y: int) -> int:

    return x + y

annotation Variables:-
we can annotate a variable using ":" colon sign proceeding with the data type 

variable_name : data_type = value 

===============================
from typing import Optional

def get_name(prefix: Optional[str]) -> str:
    if prefix:
        return prefix + "John"
    return "John"
======================================

python if __name__ == "__main__" : why we use it

 sample.py

==========================

def fun():

return "hello"

fun()

if __name__ == "__main__" :

print ("This will run when the script will run directly like python sample.py and not imported.")


Python Modules Importing

 my_module.py

==========================

def greet(name):
    return f"Hello, {name} !!!"
class MyClass :
    def __init__(self,value):
        self.value = value 
    def display_value(self):
        print(f"value : {self.value}")

========================

another_script.py

===========================

import my_module
print(my_module.greet("India"))
# create MyClass obj for accessing its methods 
obj = my_module.MyClass(50)
obj.display_value()

===========================

How to import C:\Users\India\Desktop\sample.py into E:\folder\second.py  using python :

==================================================

 my_module.py

==========================

def greet(name):
    return f"Hello, {name} !!!"
class MyClass :
    def __init__(self,value):
        self.value = value 
    def display_value(self):
        print(f"value : {self.value}")

==============================

second.py 

=============================

#import sys 
import sys
# import my_module absolute path 
sys.path.append('C:/Users/India/Desktop')
# import module now 
import my_module
# use methods of my_module 
print(f"The greet() methods from my_module file : {my_module.greet("India")}")
# use MyClass methods 
obj = my_module.MyClass(50)
obj.display_value()

=============================================================

Thursday, September 28, 2023

Python File Handling

#!/usr/bin/python
import os, sys
# open a file 
fd = os.open("file.txt", os.O_RDWR|os.O_CREAT)
# write one string
os.write(fd, "This is written in the file.txt")
# close opened file 
os.close(fd)
print("closed the filed successfully")
=============================================================
os.O_RDONLY − open for reading only
os.O_WRONLY − open for writing only
os.O_RDWR − open for reading and writing
os.O_NONBLOCK − do not block on open
os.O_APPEND − append on each write
os.O_CREAT − create file if it does not exist
os.O_TRUNC − truncate size to 0
os.O_EXCL − error if create and file exists
os.O_SHLOCK − atomically obtain a shared lock
os.O_EXLOCK − atomically obtain an exclusive lock
os.O_DIRECT − eliminate or reduce cache effects
os.O_FSYNC − synchronous writes
os.O_NOFOLLOW − do not follow symlinks

============================================================
import os, time, sys

file_path = "/path/to/your/file"  # Replace with the path to your file

try:
    # Get the ctime using os.stat
    ctime = os.stat(file_path).st_ctime

    # Convert ctime to a formatted string with AM/PM
    formatted_ctime = time.strftime("%d-%m-%Y %I:%M:%S %p", time.localtime(ctime))

    print("Formatted ctime:", formatted_ctime)

except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print("An error occurred:", str(e))
==============================================================

%d-%m-%Y %I:%M:%S %p :- %p will show am/pm 
==============================================================
os.system("linux command")
os.path.join(path,"file_name_to_attach")
os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)
os.path.relpath(path)
os.path.abspath(path)
os.path.getsize(path/(1024*1024*1024)  # gives size in gb
os.path.basename(path)    # works same like dirname in linux 

for root,dirs,files in os.walk(path):
    for file in files :
        print(f"This is a file  : {file}")
    for dir in dirs :
        print(f"This is a directory : {dir}")
======================================================

os.truncate(file_path,new_size_bytes)

=====================================================
#!/usr/bin/python3.6


#import os module
import os, sys

# use os.walk to get traverse files and directories
# loop all directory and file from mention path
# get the user prompt for path

file_search = input("Enter your file: ")

for root,dirs,files in os.walk('/'):
    for name in files :
        if name == file_search:
            print(os.path.abspath(os.path.join(root,name)))
=======================================================
sample.py
print(os.path.abspath(__file__)) # will give absolute path of python script  like /home/oracle/sample.py

+++++++++++++++++++++++++++++++++++++++++++++++++++++++
os.startfile("file.xls","edit")
os.startfile("file.xls","open")
os.startfile("file.xls","print")

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...