How to move files from one directory to two other directories using if else conditions…
- User
How to move files from one directory to two other directories using if else conditions in Python
Assistant
Below is a step-by-step guide on how to move files from one directory to two other directories based on
if-elseconditions using Python. This example will use theshutilmodule for moving files andosfor interacting with the operating system (e.g., checking if files/directories exist).Prerequisites:
- Python installed on your system.
- The source directory and the two target directories already exist.
- You have the necessary permissions to read from the source directory and write to the target directories.
Python Script:
pythonimport os import shutil import logging # Set up logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Define directories SOURCE_DIR = '/path/to/your/source/directory' TARGET_DIR_1 = '/path/to/your/first/target/directory' TARGET_DIR_2 = '/path/to/your/second/target/directory' # Condition function (example: move files based on file extension) def decide_move_destination(file_name): # Example condition: Move .txt files to TARGET_DIR_1, otherwise to TARGET_DIR_2 if file_name.endswith('.txt'): return TARGET_DIR_1 else: return TARGET_DIR_2 def main(): # Check if directories exist for dir in [SOURCE_DIR, TARGET_DIR_1, TARGET_DIR_2]: if not os.path.isdir(dir): logging.error(f"Directory {dir} does not exist. Please create it and try again.") return # Iterate over all files in the source directory for filename in os.listdir(SOURCE_DIR): # Construct full file path file_path = os.path.join(SOURCE_DIR, filename) # Check if it's a file (not directory) if os.path.isfile(file_path): # Decide the target directory based on the condition target_dir = decide_move_destination(filename) target_file_path = os.path.join(target_dir, filename) if os.path.exists(target_file_path): logging.warning(f"File {filename} already exists in {target_dir}. Skipping to avoid overwrite.") continue try: # Attempt to move the file shutil.move(file_path, target_dir) logging.info(f"Successfully moved {filename} to {target_dir}") except Exception as e: logging.error(f"Failed to move {filename}: {str(e)}") if __name__ == "__main__": main()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.