pythonpermissionsshutilhard-drivepython-os

How do I run a Python file on my Mac that reads and writes txt files to my external hardrive?


I currently have a folder full of epubs that I would like to read, a folder of epubs I've already read and would like to read again, and a corresponding file with the names of the epub files in each. The problem is, these folders are on my external hard-drive only. What I want to do is to have my script parse the list of epubs in these folders and create an up-to-date copy in my downloads folder, where another bit of code will take care of any copies I download if I forget that I already have a copy in my library.

I imagine that this fix will have to make use of the os or shutil modules, and I've been told to be very careful when making use of them. I do understand that this might also require use of Bash, which I have some minor inkling of knowledge in.


Solution

  • I'm not too sure on what your asking but maybe this is what you want?

    import os
    import shutil
    
    # Paths
    external_drive_folder = '/path/to/external/drive/folder'
    downloads_folder = '/path/to/downloads/folder'
    read_list_file = '/path/to/read_list.txt'
    to_read_list_file = '/path/to/to_read_list.txt'
    
    # Read the list of epub files
    def read_file_list(file_path):
        with open(file_path, 'r') as file:
            return [line.strip() for line in file]
    
    read_list = read_file_list(read_list_file)
    to_read_list = read_file_list(to_read_list_file)
    
    # Combine the lists
    all_epub_files = read_list + to_read_list
    
    # Function to copy files
    def copy_files(file_list, src_folder, dst_folder):
        for file_name in file_list:
            src_path = os.path.join(src_folder, file_name)
            dst_path = os.path.join(dst_folder, file_name)
        
            # Check if the file already exists in the destination folder
            if os.path.exists(dst_path):
                print(f"File {file_name} already exists in the destination folder.")
            else:
                try:
                    shutil.copy2(src_path, dst_path)
                    print(f"Copied {file_name} to {dst_folder}.")
                except Exception as e:
                    print(f"Error copying {file_name}: {e}")
    
    # Copy files from external drive to downloads folder
    copy_files(all_epub_files, external_drive_folder, downloads_folder)
    

    I'm not too sure on how well this code will run, but hope it works out for you.