python 根据 df 值将文件移动到文件夹

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

我是Python中路径使用和移动文件的新手。 我的目标是将我的文件分类到不同的“类文件夹”中,以便之后对它们进行分类。 为了对它们进行排序,我添加了一列,其中包含每个文件的当前位置。 我正在尝试创建移动目标文件夹中的所有这些文件(每个文件不同)

image_path 是我的文件的当前位置(全部位于同一目录中,包括文件名和扩展名) ipath 是文件的目标文件夹(包括文件名和扩展名) 我已经为所有文件创建了所有目标目录 preview of my df

这是我的代码:

#initialisation of variables used
ip = ''
imp = ''
for image_name in rkt_merged.image_name:
    #attribution of path to variables
    ip = ipath
    imp = image_path
    #
    filePath = shutil.move(image_path, ipath)

收到的错误如下,我不明白“FileNotFoundError:[Errno 2]没有这样的文件或目录:'' 我怀疑我的变量没有从我的 df 获取值。

我还尝试了以下枚举循环:

for ipath, image_path in enumerate(rkt_merged.image_name):
    filePath = shutil.move(image_path, ipath)

并收到以下错误: 重命名:dst 应该是字符串、字节或 os.PathLike,而不是 int

显示我的变量时,一切似乎都是正确的。 谢谢你的帮助

python dataframe file directory move
1个回答
0
投票

错误消息 FileNotFoundError: [Errno 2] No such file or directory: '' 表示您尝试移动的文件不存在。我认为,在您的情况下,文件路径为空,这就是您收到此错误的原因。

如果是这种情况,要修复它,您需要确保将 image_path 变量设置为正确的文件路径。您可以通过迭代 DataFrame 的行并获取每行的 image_name 列的值来完成此操作。例如:

import shutil

# Get the current working directory
cwd = os.getcwd()

# Iterate over the rows of the DataFrame
for index, row in rkt_merged.iterrows():
    # Get the image name
    image_name = row['image_name']

    # Get the current file path
    image_path = os.path.join(cwd, image_name)

    # Get the target file path
    ipath = os.path.join(cwd, 'target_folder', image_name)

    # Move the file
    shutil.move(image_path, ipath)

此代码将迭代 DataFrame 的行并将每个文件移动到目标文件夹。

请注意,您可能需要将 cwd 变量修改为正确的工作目录。您还可以将 target_folder 变量修改为所需的目标文件夹。

我希望这有帮助!

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