Table of contents

  1. Rename and move file with Python
  2. Move an email in GMail with Python and imaplib
  3. Build a Bulk File Rename Tool With Python and PyQt

Rename and move file with Python

To rename and move a file using Python, you can use the os module, which provides functions for working with files and directories. Here's how you can rename and move a file:

import os

# Define the source file path and new file name
source_file = 'old_file.txt'
new_file_name = 'new_file.txt'

# Define the destination directory path
destination_directory = 'destination_folder'

# Construct the new path for the renamed file
new_file_path = os.path.join(destination_directory, new_file_name)

# Rename and move the file
os.rename(source_file, new_file_path)

print(f"File '{source_file}' has been renamed to '{new_file_name}' and moved to '{destination_directory}'.")

In this example:

  1. Replace 'old_file.txt' with the path of the file you want to rename and move.
  2. Replace 'new_file.txt' with the new name you want for the file.
  3. Replace 'destination_folder' with the path of the directory where you want to move the file.

The os.rename() function is used to rename the file. It takes two arguments: the current file path and the new file path.

Keep in mind that the os.rename() function will raise an exception if the source file doesn't exist, the destination directory doesn't exist, or if the destination file already exists. You can use os.path.exists() to check if the source file exists and handle these cases accordingly.

Additionally, if you want to move a file across different drives or partitions, you might need to use shutil.move() instead of os.rename() as it provides more capabilities for handling different file system locations.


Move an email in GMail with Python and imaplib

To move an email in Gmail using Python and the imaplib library, you can use the imaplib module to connect to your Gmail account, search for the email you want to move, and then move it to the desired folder (label). Here's a step-by-step guide on how to do this:

  1. Enable IMAP in your Gmail account:

    Before you can use the imaplib library, make sure that IMAP access is enabled in your Gmail settings. You can do this by following these steps:

    • Log in to your Gmail account.
    • Click on the gear icon in the upper-right corner and select "See all settings."
    • Go to the "Forwarding and POP/IMAP" tab.
    • Under the "IMAP access" section, select "Enable IMAP."
    • Save your changes.
  2. Install the imaplib library:

    If you don't already have the imaplib library, you can install it using pip:

    pip install imaplib
    
  3. Use the following Python code to move an email:

    Replace [email protected], your_password, source_folder, target_folder, and search_criteria with your Gmail credentials and desired folder names and search criteria.

    import imaplib
    from email.header import decode_header
    
    # Gmail credentials
    email = "[email protected]"
    password = "your_password"
    
    # Source folder (label) and target folder (label)
    source_folder = "INBOX"
    target_folder = "Target Label"
    
    # Search criteria (e.g., subject or sender)
    search_criteria = 'Your Search Criteria'
    
    # Connect to Gmail's IMAP server
    mail = imaplib.IMAP4_SSL("imap.gmail.com")
    
    # Log in to your Gmail account
    mail.login(email, password)
    
    # Select the source folder
    mail.select(source_folder)
    
    # Search for emails based on search criteria
    status, email_ids = mail.search(None, f'(SUBJECT "{search_criteria}")')
    
    # Move matching emails to the target folder
    for email_id in email_ids[0].split():
        mail.copy(email_id, target_folder)
        mail.store(email_id, '+FLAGS', '(\Deleted)')
    mail.expunge()
    
    # Close the mailbox and logout
    mail.close()
    mail.logout()
    

    This code connects to your Gmail account, searches for emails matching the specified criteria in the source folder, copies them to the target folder (label), and marks them as deleted in the source folder.

Make sure to replace [email protected], your_password, source_folder, target_folder, and search_criteria with your specific values. Also, consider using more secure methods to store and manage your credentials, such as environment variables or configuration files, especially if this script is intended for production use.


Build a Bulk File Rename Tool With Python and PyQt

Building a bulk file rename tool involves creating a graphical user interface (GUI) that lets users select multiple files and rename them based on a specific pattern. For this example, I'll build a simple bulk file rename tool that uses PyQt5 to create the GUI. The tool will allow users to select a directory, define a naming pattern, and then rename all files in the directory according to the specified pattern.

1. Install Required Packages:

pip install PyQt5

2. Create the Tool:

import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QFileDialog, QLineEdit, QLabel

class RenamerApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # Widgets
        self.dirLabel = QLabel("Directory: Not Chosen", self)
        self.chooseDirBtn = QPushButton("Choose Directory", self)
        self.namePatternLineEdit = QLineEdit(self)
        self.renameBtn = QPushButton("Rename Files", self)

        # Layout
        layout.addWidget(self.dirLabel)
        layout.addWidget(self.chooseDirBtn)
        layout.addWidget(QLabel("New Naming Pattern (use {0}, {1} etc. for numbering):"))
        layout.addWidget(self.namePatternLineEdit)
        layout.addWidget(self.renameBtn)

        self.chooseDirBtn.clicked.connect(self.chooseDirectory)
        self.renameBtn.clicked.connect(self.renameFiles)

        self.setLayout(layout)
        self.setWindowTitle('Bulk File Renamer')
        self.setGeometry(400, 400, 400, 200)

    def chooseDirectory(self):
        dir_path = QFileDialog.getExistingDirectory(self, "Select Directory")
        if dir_path:
            self.dirLabel.setText(f"Directory: {dir_path}")

    def renameFiles(self):
        dir_path = self.dirLabel.text().replace("Directory: ", "")
        if not dir_path or dir_path == "Not Chosen":
            return

        naming_pattern = self.namePatternLineEdit.text()
        if not naming_pattern:
            return

        try:
            for idx, filename in enumerate(os.listdir(dir_path)):
                file_extension = os.path.splitext(filename)[1]
                new_name = naming_pattern.format(idx) + file_extension
                os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_name))
            self.dirLabel.setText("Renaming completed!")
        except Exception as e:
            self.dirLabel.setText(str(e))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = RenamerApp()
    ex.show()
    sys.exit(app.exec_())

How to Use the Tool:

  1. Launch the script.
  2. Click "Choose Directory" and select the directory containing the files you want to rename.
  3. Input a naming pattern in the text field. Use {0}, {1}, etc. to indicate where you want the file numbers to appear.
  4. Click "Rename Files".

For example, if the naming pattern is file_{0}, the files will be renamed as file_0, file_1, file_2, etc.

This is a basic tool. To make it more advanced, you can add more features, like renaming only specific file types, including more advanced patterns, or providing undo functionality.


More Python Questions

More C# Questions