首页 > 解决方案 > 如何在目录中移动文件而不是文件夹?

问题描述

我创建了一个简单的 Python 脚本来将文件从文件夹/目录移动到同一路径中新创建的文件夹。这个想法是移动超过五天前修改过的文件。我在移动基本路径中的所有内容时遇到问题,包括其他子文件夹。有没有办法只移动文件而不是文件夹?

我尝试了模块中的.endswith功能os.path,但没有运气。我相信我错过了一些围绕通配符的东西。

这是我的代码:

if not os.path.exists(new_path):
    os.mkdir(new_path)
    print('Successfully created the directory %s' % new_path)
else:        
    print('The directory %s already exists' % new_path)

for f in os.listdir(dir_path):
    path_and_file = os.path.join(dir_path,f)
    if int((datetime.datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d")).replace("-","")) < int(threshold_date.replace("-","")):
        destpath_and_file = os.path.join(new_path, f)
        shutil.move(path_and_file,destpath_and_file)

该代码有效,移动了基本文件夹中的所有内容。但是,它也在移动子文件夹。我只想移动文件。(例如,仅移动 .xls/.xlsx 文件。)

非常感谢。

标签: pythonshutil

解决方案


使用 os.path.isfile() 检查 f 是不是一个文件。

for f in os.listdir(dir_path):
    if os.path.isfile(f):
        ...


推荐阅读