n4s is a feature rich Python package that makes writing pythonic code easier and more intuative
using libraries that already come packaged with Python 3.
* with one exception
There are currently four core modules:
- fs - interacts with your file system
- strgs - manipulates strings and lists
- term - console / terminal commands
- web - series of web oriented tools
Because writing Python code shouldn't be hard or tedious - regardless of experience and skill level. This library expedites basic Python functionality, so you can focus on the more complex modules of your applications. This will help you save dev time, make your code cleaner and elminiate redundancy.
The file system module contains a series of helpful tools for interacting with your file system and completing various tasks.
These tools include:
from n4s import fs
Functions:
All of these functions include simple and intuative ways to verify the integrity of your task execution, such as checking file and directory paths when moving files around, with the option to create directories if they don't exist, setting naming conventions for multiple copies of a file, verifying file extensions, and more.
Copies files / directories, either individually or as a list
fs.copy_file()
fs.copy_file(Source: Path,
Destination: Path='',
overwrite: bool=False,
debug: bool=False)
Source: Path
## Path to a file, or a list of files
## Single File:
'../file.jpeg'
## List of Files:
['../file1.jpeg', '../file2.jpeg', '../file3.jpeg']
Destination: Path=''
## Destination of the newly copied file, either as a file path or a directory path
## File Path:
'../Pictures/file.jpeg'
## Directory Path:
'../Pictures/'
overwrite: bool=False
## Whether or not to overwrite files with the same name and extension
## False:
'../Pictures/file(1).jpeg' # Increases quantitatively
## True:
'../Pictures/file.jpeg' # New file
debug: bool=False
## Prints operation task to terminal
## When a Source is not found or a Destination cannot be created
"n4s.fs.copy_file():"
"Does Not Exist => {Source}"
## When the operation finishes
"n4s.fs.copy_file():"
"Source => {Source}"
"Destination => {Destination}"
## Other errors...
Single File
fs.copy_file(Source='Users/need4swede/Downloads/shrek_meme.jpg',
Destination='Users/need4swede/Pictures/')
List of Files
fs.copy_file(Source=['Users/need4swede/Downloads/song1.mp3',
'Users/need4swede/Downloads/song2.mp3',
'Users/need4swede/Downloads/song3.mp3'],
Destination='Users/need4swede/Music/')
Overwrite a File
fs.copy_file(Source='Users/need4swede/Desktop/notes.txt',
Destination='Users/need4swede/Documents/notes.txt',
overwrite=True)
Path Verification
If a Destination path does not exist or cannot be found when copying a file, it will automatically be created. To accomplish this, the path_exists function is used from the n4s Path Finder to verify path integrity. This ensures that you don't have to worry about whether or not a directory or path exists prior to copying your files, as they will be created for you whenever possible.
File Path vs Directory
Your Destination can either be a file path or a directory. If it's a file path, then you will have to explicitly name the new file. If it's a directory path, the new file will inherit its name from the Source file. This means no more having to individually name each file if you don't want to, or catching an error because you didn't explicitly pick a file path as your copy destination. This also means that you don't have to worry about file extensions as it inherits this information directly from the Source. You can, of course, override this functionality by explicitly declaring a file extension when copying a file.
Handling Duplicates
If an identical file exists at any given Destination path, the new file will contain a numerical suffix to differentiate the copies. This number quantifies with each iteration if multiple files are being copied at once.
Source Not Found
If a Source path is incorrect or a file cannot be located, your program won't automatically crash. Of course, if your application relies on the existance of a file that was not copied, it will throw a FileNotFound error, but the copy_file function will not. This allows you to call the function without having to add unecessary try and except blocks to your code. The path_exists function from the n4s Path Finder allows you to check if a file or directory exists if you need to validate this action later in your code. I will go over these tools further down the documentation.
fs.copy_file operates silently by default, so you would have to enable the debug feature to see if a file was not found.
Reads file extensions from input paths
fs.read_format()
fs.read_format(Input: str,
Include_Period: bool=False,
Print: bool=False,
Uppercase: bool=False,
Read_Filename: bool=False)
Input: str
## Input string, usually a path to a local file or a web address
## Examples:
'../photo.jpeg' # jpeg
'../word.doc' # doc
'../adobe.pdf' # pdf
Include_Period: bool=False
## Whether or not to include the period along with the format
## False:
'../photo.jpeg' # jpeg
## True:
'../photo.jpeg' # .jpeg
Print: bool=False
## Whether or not to print the returning value to your terminal
## False by default
Uppercase: bool=False
## Returns the format in uppercase characters
## False:
'../photo.jpeg' # jpeg
## True:
'../photo.jpeg' # JPEG
Read_Filename: bool=False
## Returns the name of a file
## True:
'../my_resume.pdf' # my_resume
## You need to have Include_Period set to True, otherwise the
## period is associated with the filename, as opposed to the extension.
Default
fs.read_format('../audio.mp3') ## mp3
Include Period and Uppercase
example_file = '/Videos/sample_video.avi'
fs.read_format(example_file, True, Uppercase=True) ## .AVI
Read Filename with Include_Period
website_logo = 'https://www.need4swede.net/../logo.png'
filename = fs.read_format(website_logo, True, Read_Filename=True) ## Read filename, include period
print(filename) # logo
File Selection
Reference files without having to know their file extensions. This can be really useful when working on a project that has a high throughput of files that all have different formats. You can simply reference a file's name and use fs.read_format(Input=str, Include_Period=True) to get a valid file path.
Validate Extensions
When saving a file from the web, sometimes file extensions change or get omitted altogether. fs.read_format can help you avoid such issues by validating proper extensions when downloading files.
Read Filenames
The Read_Filename argument can help you curate a directory of files, or compare the names of files, even if they have different extensions. You can also use this to filter duplicates, if you have the same file in different extensions.
Deletes files / directories, either individually or as a list
fs.remove_file() # Deletes files
fs.remove_dir() # Deletes directories and nested content
fs.remove_file(File: Path,
debug: bool=False)
fs.remove_dir(Directory: Path,
debug: bool=False)
File / Directory: Path
## Path to a directory/file or a list of directories/files
## Single File:
'../file.jpeg'
## List of Files:
['../file1.jpeg', '../file2.jpeg', '../file3.jpeg']
## Single Directory:
'../photos'
## List of directories:
['../photos', '../pictures', '../pics']
debug: bool=False
## Prints operation task to terminal
## When a File or Directory is not found
"n4s.fs.remove_file():"
"Does Not Exist => {File}"
## When the operation finishes
"n4s.fs.remove_file():"
"Removed => {File}"
## Other errors...
Single File
fs.remove_file('Users/need4swede/Downloads/shrek_meme.jpg')
List of Files
fs.remove_file(['Users/need4swede/Downloads/song1.mp3',
'Users/need4swede/Downloads/song2.mp3',
'Users/need4swede/Downloads/song3.mp3'])
Remove a Directory and nested content
fs.remove_dir('Users/need4swede/memes')
Remove a list of Directories
fs.remove_dir(['Users/need4swede/memes',
'Users/need4swede/oldphotos',
'Users/need4swede/codingstuff'])
File Path vs Directory
Your File / Destination can either be a file path or a directory. If you are removing a directory, all the files (and sub directories) within will also be removed. You can remove multiple files at once using a list to selectively remove content within a directory without effecting neighboring files or folders. Source file. This means no more having to individually name each file if you don't want to, or catching an error because you didn't explicitly pick a file path as your copy destination. This also means that you don't have to worry about file extensions as it inherits this information directly from the Source. You can, of course, override this functionality by explicitly declaring a file extension when copying a file.
Source Not Found
If a File / Directory path is incorrect or a file cannot be located, your program won't automatically crash. This allows you to call the function without having to add unecessary try and except blocks to your code. The path_exists function from the n4s Path Finder allows you to check if a file or directory exists if you need to validate this action later in your code. I will go over these tools further down the documentation.
fs.remove_file and fs.remove_dir operate silently by default, so you would have to enable the debug feature to see if you encountered an error.
Renames files and directories
fs.rename()
fs.rename(Name: Path,
Rename: str=''
debug: bool=False)
Name: Path
## Path to the file/directory that you want to rename
## File:
'../file.jpeg'
## Directory:
'../photos'
Rename: Path
## The new name for the file/directory
## File:
'photograph.jpeg'
## Directory:
'pictures'
debug: bool=False
## Prints operation task to terminal
## When the operation finishes
"n4s.fs.rename():"
f"Name => {Name}"
f"Rename => {Rename}")
## Other errors...
File
fs.rename('Users/need4swede/Downloads/photo.jpg', 'dog.jpg') '../Downloads/dog.jpg'
File with Format Inheritance
fs.rename('Users/need4swede/Music/song.mp3', 'all_star') '../Music/all_star.mp3'
Directory
fs.rename('Users/need4swede/Documents/Homework', 'Homework_2022') '../Documents/Homework_2022'
File Path vs Directory
Your Name argument can either be a file path or a directory. The distinction is derived from the inclusion of a file extension. If you don't explicitly pass a file extension, then the path will be treated as a directory.
Format Inheritance
If your Rename doesn't explicitly declare a file extension, then fs.rename will automatically inherit the file extension from your Name parameter. Consequently, explicit extension declerations will result in your files having their file extensions altered!
Source Not Found
If a Name path is incorrect or a file cannot be located, your program won't automatically crash. This allows you to call the function without having to add unecessary try and except blocks to your code. The path_exists function from the n4s Path Finder allows you to check if a file or directory exists if you need to validate this action later in your code. I will go over these tools further down the documentation.
fs.rename operates silently by default, so you would have to enable the debug feature to see if you encountered an error.
Functions:
The fs.mail module allows you to compose mail with recipient, subject, body and attachment properties.
fs.mail()
fs.mail(Send_To: str='',
Subject: str='',
Body: str='',
Attachment: Path='')
Send_To: str
## Email address of the recipient
## Example:
'jdoe@company.com'
Subject: str
## The subject line of the email
## Example:
'RE: n4s mail composer'
Body: str
## Message body of the email
## Short Example:
'This is a short message'
## Long Example:
'''
This is a longer message.
You can write whatever you want
and it will be included in the body.
'''
Attachment: Path
## Add file attachments to your email
## Example:
'../User/Pictures/dog.png'
Generate Mailto
fs.mail('email@domain.com')
Compose Short Message
fs.mail('email@domain.com',
'RE: Mail Handler',
'Welcome to n4s!')
Compose Long Message
address = 'shrek@swamp-mail.org'
subject = 'RE: All Star'
message = '''
Somebody once told me the world is gonna roll me
I ain't the sharpest tool in the shed
She was looking kind of dumb with her finger and her thumb
In the shape of an "l" on her forehead
Well the years start coming and they don't stop coming
Fed to the rules and I hit the ground running
Didn't make sense not to live for fun
Your brain gets smart but your head gets dumb
So much to do so much to see
So what's wrong with taking the back streets
You'll never know if you don't go
You'll never shine if you don't glow
'''
fs.mail(address, subject, message)
Send Attachments
fs.mail('email@domain.com', # Recipient
'Important File', # Subject
'Here is the file you requested', # Message Body
'../Documents/important.pdf') # Path to file
Mail Call
Create the Python equivalent of a mailto anchor in HTML by calling the fs.mail function from your program and launching your system's mail application.
Conditional Attachments
Easily add file attachments to your messages and filter them by recipient and/or subject line, giving you an easy and autonomous way of associating certain attachments based on certain conditions.
Dynamic Composition
The fs.mail composer allows you to compose emails dynamically with the use of variables. Using simple conditional statements and string formation, you can create various pipelines composed of dynamic entries, such as email addresses, subject line's and even entire messages.
Functions:
The Path Finder includes simple and intuative ways to verify the integrity of your task execution, such as checking file and directory paths, with the option to create them if they don't exist.
It also includes quick and easy ways to access certain root directories on a system, from user folders to applications
Verifies the existance of a given path, or a list of paths, with the option to create them if they do not exist
fs.path_exists()
fs.path_exists(Path: Path,
Make: bool=False,
debug: bool=False)
Path: Path
## Path to a file or directory, or list of either or both
## Single File:
'User/need4swede/Pictures/Memes/photo.jpeg'
## Directory:
'User/need4swede/Pictures/Memes'
## List of Files & Directories:
['User/need4swede/Music/Memes',
'User/need4swede/Music/Memes/Favorites',
'User/need4swede/Pictures/Memes/photo1.jpeg',
'User/need4swede/Pictures/Memes/photo2.jpeg']
Make: bool=False
## Create directory / file if it does not exist
debug: bool=False
## Prints operation task to terminal
## When a file path exists
"n4s.fs.path_exists():"
"File Exist => {'/Users/need4swede/Desktop/file.txt'}"
## When a make a file that did not previously exist
"n4s.fs.path_exists():"
"Created File => {'/Users/need4swede/Desktop/new_file.txt'}"
## Other operations...
File Exists
fs.path_exists('Users/need4swede/Downloads/shrek_meme.jpg') # True
List of Files
fs.path_exists(['Users/need4swede/Downloads/song1.mp3' # True
'Users/need4swede/Downloads/song2.mp3', # False
'Users/need4swede/Downloads/song3.mp3'], # True
Create a directory if it does not exist
ls /Users/need4swede/Documents
coding
homework
doc.pdf
fs.path_exists('Users/need4swede/Documents/Notes', True) # Creates => ../Documents/Notes
ls /Users/need4swede/Documents
coding
homework
Notes
doc.pdf
fs.path_exists('Users/need4swede/Documents/Notes', True) # True, nothing else created
Path Verification
If a Destination path does not exist or cannot be found when copying a file, it will automatically be created. To accomplish this, the path_exists function is used from the n4s Path Finder to verify path integrity. This ensures that you don't have to worry about whether or not a directory or path exists prior to copying your files, as they will be created for you whenever possible.
File Path vs Directory
Your Destination can either be a file path or a directory. If it's a file path, then you will have to explicitly name the new file. If it's a directory path, the new file will inherit its name from the Source file. This means no more having to individually name each file if you don't want to, or catching an error because you didn't explicitly pick a file path as your copy destination. This also means that you don't have to worry about file extensions as it inherits this information directly from the Source. You can, of course, override this functionality by explicitly declaring a file extension when copying a file.
Handling Duplicates
If an identical file exists at any given Destination path, the new file will contain a numerical suffix to differentiate the copies. This number quantifies with each iteration if multiple files are being copied at once.
Source Not Found
If a Source path is incorrect or a file cannot be located, your program won't automatically crash. fs.path_exists operates silently by default, so you would have to enable the debug feature to print errors.
Points to various common directories and sub-directories on a local file system
fs.root()
fs.root(Directory: str='user',
debug: bool=False)
Directory: str
## Choice of directory - default is 'user'
## Examples:
'applications' or 'apps' # root of '/Applications' or 'Program Files' directory
'desktop' or 'desk' # local user's 'Desktop' directory
'documents' or 'docs' # local user's 'Documents' directory
'downloads' or 'dl' # local user's 'Downloads' directory
'user' # root of local user directory
'userlib' # root of 'User/Library' or 'AppData' directory
'syslib' # root of '/Library' or 'System32' directory
debug: bool=False
## Prints the full path of the chosen directory to the terminal
Default
fs.root() ## root of user directory
Documents
fs.root('docs')
## macOS => /$USER/Documents
## Windows => C:\Users\$USER\Documents
User Library
fs.root('userlib')
## macOS => /$USER/Library
## Windows => C:\Users\$USER\AppData
Navigation
Reference directories with ease without having to type their full paths. This can be really useful when working on a project that requires the use of certain directories without knowing exact path names.
Account Names
Since fs.root returns a string, you can use this to get the username of an account on any system.
Cross-Platform Compatible
You don't have to make exceptions for macOS and Windows applications in your code. fs.root uses the same arguments and handles directories differently based on the operating system, so you don't have to worry about changing anything. Of course you can make amendments if deemed necessary.
Functions:
System allows for intuative ways to interact with other parts of your operating system. It can be used to start applications, check if something is installed, validate what version you're running and even control python code with simple commands.
System commands for checking and launching installed applications
fs.system('app-')
fs.system(Action: str,
Print: bool=False)
Action: str='app-'
## Launch an application
fs.system('app-APPNAME')
## Check if an application is installed
fs.system('app-APPNAME-installed')
## Printa a list of all installed applications
fs.system('app-list')
Print: bool=False
## Prints info to the terminal
Launch MS Word
fs.system('app-microsoft word') # Starts MS Word
Check if Discord is installed
fs.system('app-discord-installed') # True / False
App Launcher
Conveniently launch apps directly from your python code without having to configure any complex commands or shell scripts.
Verify Installs
Easily verify whether or not an application has been installed on the system. You can also check to see if a combination of applications are installed.
Returns information about your system
fs.system('info')
fs.system(Action: str,
Print: bool=False)
fs.system('info')
## Returns an array of [os_type, os_version, chip_architecture]
Print: bool=False
## Prints info to the terminal
Apple M1 Macbook
fs.system('info') # ['macOS', '12.4', 'arm64']
Windows on AMD CPU
fs.system('info') # ['Windows', '10', 'AMD64']
Verify OS version (macOS)
os_type = fs.system('info')[0] # ['macOS']
os_version = fs.system('info')[1] # ['12.4']
if os_type == 'macOS' and int(os_version) => 12.2:
## Do something...
Read OS Versions
Easily read what version of a given operating system the code is being excecuted on, with the ability to differentiate them for app support and debugging.
Some helpful Python commands
fs.system('python')
fs.system(Action: str,
Print: bool=False)
Action: str='python'
## Returns Python Version
fs.system('python-restart')
## Restarts your python application
fs.system('python-exit')
## Quits your python application
Print: bool=False
## Prints info to the terminal
Python Commands
fs.system('python') # 3.9.12
fs.system('python-exit') # exits application
Get Python Version
Cater your code for different versions of Python (useful for imports and certain libraries) or for debugging.
Restarting / Quitting Code
Easily restart your app with one command, and exit out just as easily.
Validates a System's Environment
fs.system('is-')
fs.system(Action: str,
Print: bool=False)
Action: str='is-'
fs.system('is-NAME_OF_OS')
## Validate Operating System
fs.system('is-NAME_OF_ARCH')
## Validate System Architecture
fs.system('is-hidden-PATH_TO_FILE')
## Validate if directory / file is hidden
Print: bool=False
## Prints info to the terminal
Validate Operating System
fs.system('is-mac') # Returns 'True' if macOS
fs.system('is-windows') # Returns 'True' if Windows
Validate if running on ARM processor
fs.system('is-arm') # True / False
Validate an OS
Easily check if a system is running macOS / Windows / Linux, and incpororate conditions allowing your applications to be more modular.
x86 / ARM Validation
Allows you to conveniently check a system's architecture when creating applications.
The strgs module contains a series of helpful functions for manipulating lists and strings.
With strgs, you can:
from n4s import strgs
Allows you to clean-up text by stripping away special characters, and output formatted text in various styles.
strgs.clean_text()
strgs.clean_text(Input: str='',
Casing: str='',
Remove_Spaces: bool=False,
Remove_Comma: bool=False,
Print: bool=False)
Input: str
## The string you want to format
## Example:
'this, is/ a Python &library>'
## Returns:
'this, is a Python library'
Casing: str
## The casing of your formatted string
## lower:
'this, is a python library'
## upper:
'THIS, IS A PYTHON LIBRARY'
## title:
'This, is a Python Library'
## camel:
'this, IsAPythonLibrary'
## spongebob:
'ThIs, iS A PyThOn lIbRaRy'
Remove_Spaces: bool
## Removes whitespaces from formatted string
## Example:
'this,isaPythonlibrary'
Remove_Comma: bool
## Removes commas from formatted string
## Example:
'this is a Python library'
Title Case a Book / Movie
strgs.clean_text('the lord of the rings', Casing='title') # The Lord of the Rings
Remove Special Characters from String
strgs.clean_text('$#&@AN/(TH^#%@ ON Y', Casing='lower', Remove_Spaces=True) # anthony
Compose a Meme
strgs.clean_text('Python is slower than C', Casing='spongebob') # PyThOn iS SlOwEr tHaN C
Removing Special Characters
Cleans-up text by removing special characters from strings, useful when you need to parse out characters.
Format Text
Easily format text to your liking, with different casing and punctionation options.
Removing Whitespaces
Quickly remove all whitespaces from strings, even ones between words.
That covers the core functions of n4s, but there's always more being added to this library. If you need additional assistance in using this package for your own application, please do not hesitate to reach out.
Install n4s and try its features out for yourself!
If you have any questionsabout how it works, feel free to contact me