根据数据框的值移动文件到文件夹
我刚开始学习在Python中使用路径和移动文件。
我的目标是把文件整理到不同的“类别文件夹”中,以便后续分类。
为了整理这些文件,我添加了一列,记录每个文件当前的位置。
我正在尝试把所有这些文件移动到目标文件夹(每个文件的目标文件夹都不同)。
image_path是我文件的当前路径(所有文件都在同一个目录下,包括文件名和扩展名)。
ipath是文件的目标文件夹(也包括文件名和扩展名)。
我已经为所有文件创建了目标目录。
这是我数据框的预览
这是我的代码:
#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] No such file or directory: ''”,我不太明白这个错误的意思。我怀疑我的变量没有从数据框中获取到值。
我还尝试了下面这个使用enumerate的循环:
for ipath, image_path in enumerate(rkt_merged.image_name):
filePath = shutil.move(image_path, ipath)
结果出现了另一个错误:rename: dst应该是字符串、字节或os.PathLike,而不是整数。
当我显示我的变量时,一切看起来都没问题。谢谢你的帮助。
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)
这段代码会遍历你的数据表的每一行,并把每个文件移动到目标文件夹。
注意,你可能需要把 cwd 变量修改为正确的工作目录。你也可以把 target_folder 变量修改为你想要的目标文件夹。
希望这能帮到你!