技術情報
- 2024年04月17日
- 技術情報
Organizing the Files easily with Python
In the digital age, we often find ourselves overwhelmed with files scattered across our computers. Whether it’s photos from last summer’s vacation, important documents for work, or music and videos for entertainment, keeping track of everything can be a challenge. But fear not! With the power of Python, you can automate the process of organizing your files into neat categories based on their types.
In this tutorial, we’ll walk you through a simple Python script that automatically organizes your files into categories like images, documents, videos, and more.
Before we dive in, make sure you have Python installed on your computer.
Step 1: Setting Up the Script
First, let’s create a Python script that will do the heavy lifting for us. Open your favorite text editor and copy the following code:
import os
import shutil
def classify_files(directory):
# Dictionary of file categories and their extensions
categories = {
'Images': ['jpeg', 'jpg', 'png', 'gif', 'bmp'],
'Documents': ['pdf', 'doc', 'docx', 'txt', 'rtf'],
'Spreadsheets': ['xls', 'xlsx', 'csv'],
'Videos': ['mp4', 'avi', 'mov', 'mkv'],
'Music': ['mp3', 'wav', 'flac', 'aac'],
'Archives': ['zip', 'rar', '7z', 'tar', 'gz']
}
# Create category directories if not exist
for category in categories.keys():
os.makedirs(os.path.join(directory, category), exist_ok=True)
# List files in the directory
files = os.listdir(directory)
# Classify files
for filename in files:
# Get file extension
_, ext = os.path.splitext(filename)
ext = ext[1:].lower() # Remove leading dot and convert to lowercase
# Classify the file into appropriate category
for category, extensions in categories.items():
if ext in extensions:
# Move the file to the corresponding category directory
source_path = os.path.join(directory, filename)
dest_path = os.path.join(directory, category, filename)
shutil.move(source_path, dest_path)
print(f"Moved '{filename}' to '{category}' category.")
break # Once classified, move to next file
def main():
# Input directory path
directory = input("Enter the directory path to classify files: ")
# Check if directory exists
if not os.path.exists(directory):
print("Directory not found.")
return
# Classify files
classify_files(directory)
print("File classification completed.")
if __name__ == "__main__":
main()
Save the file with a meaningful name like `organize_files.py`.
Step 2: Understanding the Code
Now, let’s break down what the code does:
– The script defines a dictionary of file categories and their corresponding extensions. For example, images have extensions like JPEG, PNG, etc.
– It prompts you to enter the directory path where your files are located.
– It creates category directories if they don’t exist already.
– It loops through all the files in the directory, classifies them into appropriate categories based on their extensions, and moves them to the respective category folders.
Step 3: Running the Script
Navigate to the directory where you saved the Python script using the command line or terminal. Then, run the script by typing `python organize_files.py` and press Enter.
Step 4: Sit Back and Relax
Watch as the script works its magic, organizing your files into tidy categories. Once it’s done, you will see your newly organized file system!
Conclusion
You’ve just automated the tedious task of file organization using Python. From now on, keeping your digital files organized will be a breeze. Feel free to customize the script to suit your specific needs and explore other ways Python can simplify your life.
Hope you enjoy that.
By Asahi
waithaw at 2024年04月17日 10:00:00
- 2024年03月12日
- 技術情報
Differences between C and Go programming languages
In the realm of programming languages, each one comes with its own set of strengths and characteristics, tailored to suit different needs and preferences of developers. Two prominent languages that often find themselves in comparison are C and Go (or Golang). Let’s delve into the key differences between these two languages across various aspects.
1. Memory Management
– In C, developers need to manually manage memory, allocating and deallocating it for variables. This hands-on approach gives precise control but also opens doors to memory-related bugs.
– Go takes a different route with automatic garbage collection, simplifying memory management tasks for developers and reducing the likelihood of memory leaks.
2. Concurrency
– Go shines in this department with its built-in support for concurrency. Goroutines and channels make it easier to write concurrent programs without worrying about low-level threading intricacies.
– C, lacking built-in concurrency primitives, often resorts to external threading libraries like POSIX threads, which can be more complex and error-prone.
3. Type System
– C boasts a weak static type system, allowing implicit type conversions and offering limited type checking.
– Go’s strong static type system enhances type safety and reduces common programming errors by enforcing stricter type rules.
4. Error Handling
– Go introduces a unique error handling mechanism using return values, eschewing exceptions. This approach encourages explicit error handling, leading to more robust and predictable code.
– C relies on error codes, return values, and functions like perror() for error handling, which can be less structured and more error-prone compared to Go’s approach.
5. Standard Library
– C’s standard library is minimalistic, often necessitating reliance on third-party libraries for additional functionalities.
– Go boasts a rich standard library covering a wide range of tasks, from networking to encryption, reducing the need for external dependencies and streamlining development.
6. Memory Safety
– C’s flexibility comes at a cost, as direct memory manipulation can lead to common pitfalls like buffer overflows and dangling pointers.
– Go prioritizes memory safety, employing automatic bounds checking and garbage collection to mitigate memory-related bugs, enhancing overall code reliability.
In conclusion, while C and Go share some similarities, they diverge significantly in their approach to memory management, concurrency, type systems, error handling, standard libraries, and memory safety. Understanding these differences can help developers make informed decisions when selecting the right language for their projects, based on factors such as performance requirements, ease of development, and code reliability.
Hope you enjoy that.
Asahi
waithaw at 2024年03月12日 10:00:00
Streamlining Electron.js App with Tray Icons
In the realm of desktop application development, Electron.js stands out as a robust framework for building cross-platform apps using web technologies. Among its many features, integrating tray icons can significantly enhance user experience by providing quick access to essential functionalities. Today, let’s explore how we can implement tray icons in our Electron.js application, from setup to implementation.
Setting Up A Electron.js Project
First things first, let’s set up a basic Electron.js project:
1. Initialize a new Node.js project
mkdir project_name && cd project_name
npm init -y
2. Install Electron.js
npm install electron
3. Create project files
project_name/
├── icon.png
├── index.html
├── index.js
├── node_modules
├── package.json
└── package-lock.json
– `index.html` for the application’s UI.
– `index.js` for Electron main process code.
– An icon file (`icon.png`) for the tray icon.
– add `start` command in package.json like this.
{
"name": "project_name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^29.0.1"
}
}
Implementing Tray Icon Functionality
Next, let’s dive into implementing the tray icon functionality in `index.js` file:
const { app, Tray, BrowserWindow } = require('electron');
const path = require('path');
let tray = null;
let mainWindow = null;
app.on('ready', () => {
tray = new Tray(path.join(__dirname, 'icon.png'));
mainWindow = new BrowserWindow({
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile('index.html');
tray.on('click', () => {
mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
});
});
Running Your Electron.js Application
To run Electron.js application, execute the following command in the terminal:
npm start
This command will start Electron application, and we should see the tray icon appear in our system tray. Clicking on the tray icon should toggle the visibility of the application window.
Conclusion
Integrating tray icons into Electron.js application is a straightforward process that can greatly improve user experience. Whether it’s for displaying notifications, providing quick access to features, or simply adding a professional touch to our app, tray icons are a valuable addition to any desktop application.
With Electron.js, implementing tray icons becomes seamless, allowing us to focus on crafting an exceptional user experience for our desktop application. So why not enhance our Electron.js app with a sleek tray icon for innovative ideas?
Hope you enjoy that.
By Asahi
waithaw at 2024年02月27日 10:00:00
[Unity]球体の内側に衝突判定Colliderを付与する
360球体画像の内側からアイトラッキングで視線情報を追従してどの部分を見ていたかログを取得する処理をつくっていましたが、ビルド後に視線のRayと360球体画像の内側の衝突判定がとれなくなりログに出力できないという問題が発生しました。
今回はこの問題の解決方法をシェアしたいと思います。
nishida at 2024年02月22日 10:00:00
Adding Watermarks to PDFs in Python with simple and efficient approach
In today’s digital age, the need to protect and personalize PDF documents is more crucial than ever. Whether you want to brand your documents or add a confidential watermark, Python provides a powerful and straightforward solution. In this blog, we’ll explore a simple Python script that utilizes the PyPDF2 and ReportLab libraries to effortlessly add watermarks to multiple PDF files.
Setting Up the Environment
Before diving into the script, make sure you have the required libraries installed. You can do this by running the following commands.
pip install PyPDF2
pip install reportlab
Understanding the Script
The entire script can be seen at the end. Let’s break down the key components of the script.
1. create_watermark() Function
– This function uses the ReportLab library to generate a PDF containing a customizable watermark.
– You can specify the watermark text, color, transparency, font, and rotation angle.
2. add_watermark() Function
– The core function that adds the watermark to each page of the input PDF.
– It uses PyPDF2 to merge the original PDF with the watermark PDF on each page.
3. delete_watermark_file() Function
– A utility function to delete the temporary watermark PDF file after it has been merged with the input files.
4. Command Line Arguments
– The script accepts two command line arguments:
– `–path`: The path to the directory containing the PDF files to watermark.
– `–watermark_text`: The text to be used as the watermark.
Here is the entire script.
import PyPDF2
import argparse
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib import colors
import os
def create_watermark(watermark_text, output_pdf):
pdf = canvas.Canvas(output_pdf)
pdf.translate(inch, inch) # move the current origin point(0,0) of the canvas by the current given horizontal and vertical distances
pdf.setFillColor(colors.red, alpha=0.3) # set the font color with alpha value to adjust the transparency of watermark text
pdf.setFont("Helvetica", 50) # set font and font size
pdf.rotate(45) # rotate the canvas by 45 degrees
pdf.drawCentredString(400, 100, watermark_text) # center the watermark text
pdf.save()
def add_watermark(input_pdf, output_directory, watermark_pdf):
base_filename = os.path.splitext(os.path.basename(input_pdf))[0]
output_pdf = os.path.join(output_directory, f'{base_filename}.pdf')
with open(input_pdf, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
pdf_writer = PyPDF2.PdfWriter()
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
watermark_reader = PyPDF2.PdfReader(watermark_pdf)
watermark_page = watermark_reader.pages[0]
page.merge_page(watermark_page)
pdf_writer.add_page(page)
with open(output_pdf, 'wb') as output_file:
pdf_writer.write(output_file)
def delete_watermark_file(watermark_pdf):
if os.path.exists(watermark_pdf):
os.remove(watermark_pdf)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--path", required=True, type=str, help="Path of the directory of file lists")
parser.add_argument("--watermark_text", required=True, type=str, help="Text to be watermark")
args = parser.parse_args()
path = args.path
watermark_text = args.watermark_text
print('Processing.....')
file_list = [file_name for file_name in os.listdir(path) if os.path.isfile(os.path.join(path, file_name))]
output_directory = os.path.join(path, 'output_directory')
if not os.path.exists(output_directory):
os.makedirs(output_directory)
watermark_pdf_file = os.path.join(path, 'watermark.pdf')
create_watermark(watermark_text, watermark_pdf_file)
for file_name in file_list:
if not file_name == 'watermark.pdf':
input_pdf_file = os.path.join(path, file_name)
add_watermark(input_pdf_file, output_directory, watermark_pdf_file)
delete_watermark_file(watermark_pdf_file)
print('Done!')
Running the Script
To run the script, execute the following command.
python script_name.py --path /path/to/pdf/files --watermark_text "Your Watermark Text"
The script will process each PDF file in the specified directory, add the watermark, and save the watermarked files in a newly created ‘output_directory.’
Conclusion
With this Python script, you can easily add watermarks to your PDF documents, making them visually distinctive and secure. Whether you’re protecting sensitive information or branding your documents, this solution provides a quick and efficient way to enhance your PDF files. I would recommend to look into the used libraries in details and feel free to customize the script further to suit your specific requirements, such as adjusting colors, fonts, or rotation angles for the watermark.
Ref: https://pypdf2.readthedocs.io/en/3.0.0/index.html
Ref: https://docs.reportlab.com
Asahi
waithaw at 2024年02月06日 10:00:00