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")

No comments:

Post a Comment

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 ...