Python 如何在目录中移动文件而不是文件夹?
我创建了一个简单的Python脚本,将文件从文件夹/目录移动到同一路径内新创建的文件夹。其想法是移动五天前修改过的文件。我在移动基本路径中的所有内容时遇到问题,包括其他子文件夹。有没有办法只移动文件而不移动文件夹 我从Python 如何在目录中移动文件而不是文件夹?,python,shutil,Python,Shutil,我创建了一个简单的Python脚本,将文件从文件夹/目录移动到同一路径内新创建的文件夹。其想法是移动五天前修改过的文件。我在移动基本路径中的所有内容时遇到问题,包括其他子文件夹。有没有办法只移动文件而不移动文件夹 我从os.path模块中尝试了.endswith函数,但没有成功。我相信我错过了一些围绕通配符的东西 这是我的代码: if not os.path.exists(new_path): os.mkdir(new_path) print('Successfully crea
os.path
模块中尝试了.endswith
函数,但没有成功。我相信我错过了一些围绕通配符的东西
这是我的代码:
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)
如果操作系统路径不存在(新路径):
os.mkdir(新路径)
打印('已成功创建目录%s'%new\u路径)
其他:
打印(“%s”目录已存在“%new\u路径)
对于os.listdir(目录路径)中的f:
path_和_file=os.path.join(dir_path,f)
如果int((datetime.datetime.fromtimestamp(os.path.getmtime(f)).strftime(“%Y-%m-%d”)).replace(“-”,”)
代码可以工作,移动基本文件夹中的所有内容。但是,它也在移动子文件夹。我只想移动文件。(例如,仅移动.xls/.xlsx文件。)
非常感谢。检查f是否是一个带有os.path.isfile()的文件
for f in os.listdir(dir_path):
if os.path.isfile(f):
...