Import os python example
Import os python example
Here is an example of using the os
module in Python to interact with the operating system and perform various tasks:
import os
Print current working directory
print("Current Working Directory:", os.getcwd())
Change directory
os.chdir("/path/to/new/directory")
print("New Current Working Directory:", os.getcwd())
List files and directories in a directory
print("Files and Directories in", os.getcwd(),":")
for file_name in os.listdir():
print(file_name)
Check if a file exists
file_path = "/path/to/file.txt"
if os.path.exists(file_path):
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")
Create a new directory
os.mkdir("/path/to/new/directory")
print("Directory created successfully!")
Remove an empty directory
os.rmdir("/path/to/empty/directory")
print("Empty directory removed successfully!")
Copy a file
source_file = "/path/to/source/file.txt"
destination_file = "/path/to/destination/file.txt"
os.system(f"cp {source_file} {destination_file}")
Move or rename a file
file_name = "old_file.txt"
new_file_name = "new_file.txt"
os.rename(file_name, new_file_name)
print("File renamed successfully!")
Get the size of a file
file_size = os.path.getsize(source_file)
print(f"Size of {source_file} is {file_size} bytes.")
Get the creation date and time of a file
creation_time = os.path.getctime(source_file)
print(f"{source_file} was created on {creation_time}")
Get the modification date and time of a file
modification_time = os.path.getmtime(source_file)
print(f"{source_file} was last modified on {modification_time}")
This example shows how to:
Print the current working directory usingos.getcwd()
. Change the current working directory using os.chdir()
. List files and directories in a directory using os.listdir()
and iterate over the results. Check if a file exists using os.path.exists()
. Create a new directory using os.mkdir()
. Remove an empty directory using os.rmdir()
. Copy a file using os.system()
with the cp
command. Rename or move a file using os.rename()
. Get the size of a file using os.path.getsize()
. Get the creation and modification dates/times of a file using os.path.getctime()
and os.path.getmtime()
.os module in python
The os
module in Python! It's a fundamental part of the standard library that provides a way to interact with the operating system and access various system resources.
The os
module is primarily used for tasks such as:
Here are some of the most commonly used functions in the os
module:
File operations:
os.getcwd()
: Returns the current working directory. os.chdir(path)
: Changes the current working directory to the specified path. os.mkdir(path)
: Creates a new directory at the specified path. os.rmdir(path)
: Deletes the directory at the specified path. os.rename(src, dst)
: Renames the file or directory at the source path to the destination path.
Process management:
os.system(command)
: Executes a shell command and waits for it to complete. The return value is the exit status of the process. os.execv(path, args)
: Replaces the current process with a new one by executing the specified program with the given arguments. os.kill(pid, signal)
: Sends a signal to the process with the specified ID.
System information:
os.environ.get(key)
: Returns the value of the environment variable with the specified key. os.getenv(key, default)
: Returns the value of the environment variable with the specified key. If the key is not found, returns the default value. os.urandom(size)
: Generates a random byte string of the specified size.
Miscellaneous:
os.path.join(path1, path2, ...)
: Concatenates multiple paths together, using the appropriate separator for the current platform. os.path.dirname(path)
: Returns the directory part of the specified path. os.path.basename(path)
: Returns the file name part of the specified path.
These are just a few examples of what you can do with the os
module. It's an incredibly powerful and versatile tool that allows you to interact with your operating system in ways that would be difficult or impossible without it.
For example, let's say you want to write a script that creates a new directory and files inside it. You could use the os.makedirs()
function to create the directory, and then use the open()
function to create files inside it:
import os
Create a new directory called "example"
os.makedirs("example", exist_ok=True)
Create two files inside the directory
with open(os.path.join("example", "file1.txt"), "w") as f:
f.write("This is file 1!")
with open(os.path.join("example", "file2.txt"), "w") as f:
f.write("This is file 2!")
As you can see, the os
module provides a wide range of functionality that allows you to do all sorts of interesting and useful things. Whether you're writing scripts, managing files, or interacting with processes, the os
module is an essential tool in your Python toolbox.