Python 与 Colab 集成

问题描述 投票:0回答:1

我想创建一个函数,首先为我的

Google Drive
中的文件找到匹配的单词,然后我想使用那些具有相同匹配单词的文件来创建一个新文件夹。我面临的第一个挑战是将我的
colab
与我的
Google Drive
整合起来。下面是我已经编写的一些代码。任何帮助,将不胜感激。谢谢!

import re
import glob
import os
import shutil

def find_matching_files(directory, word):
    pattern = re.compile(word)
    matching_files = []
    
    for file_path in glob.glob(os.path.join(directory, '*')):
        file_name = os.path.basename(file_path)
        if pattern.search(file_name):
            matching_files.append(file_path)

    for file_path in matching_files:
        file_name = os.path.basename(file_path)
        folder_name = re.findall(word, file_name)[0]
        folder_path = os.path.join(directory, folder_name)
        os.makedirs(folder_path, exist_ok=True)

        destination = os.path.join(folder_path, file_name)
        shutil.move(file_path, destination)

    return matching_files

python google-colaboratory
1个回答
0
投票

第1步:在Colab中安装Google Drive

为此,我们需要以下两行简单的代码:

from google.colab import drive
drive.mount('/content/drive')

请注意,Colab 会要求您授予其访问您的云端硬盘的权限(出于安全原因)。由于此过程需要相当长的时间,因此我建议在专门用于此目的的单独代码块中执行此操作。

注意:Google Colab 现在在左侧面板的文件选项卡上有一个按钮(即上面覆盖有 Google Drive 图标的文件夹),可以让您直接挂载您的驱动器,但这有什么好玩的?!


第 2 步:查找文件

现在,我们想要获取那些以字符串

"roulette"
(例如)作为子字符串的文件的文件路径。下面的代码应该可以解决问题:

import os

def find_matching_files(file_path, target_string):
    matching_files = []
    for root, dirs, files in os.walk(file_path):
        for file in files:
            if target_string in file:
                matching_files.append(os.path.join(root, file))
    return matching_files

target_word = "roulette"
matching_files = find_matching_files("/content/drive/MyDrive/test/", target_word)
print(matching_files)

第 3 步:移动文件

最后,我们要将文件移动到名为

"test2"
的文件夹(例如)。没什么大不了的!为什么我们不使用下面的代码呢?

def create_folder(folder_path):
    os.makedirs(folder_path)

def move_files_to_folder(files, folder_path):
    create_folder(folder_path)
    for file in files:
        file_name = os.path.basename(file)
        destination = os.path.join(folder_path, file_name)
        os.rename(file, destination)

folder_path = "/content/drive/MyDrive/test2"
move_files_to_folder(matching_files, folder_path)

希望这有帮助!愿代码与您同在...

© www.soinside.com 2019 - 2024. All rights reserved.