python - 如何在目录中移动文件而不是文件夹?
问题描述
我创建了一个简单的 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 文件。)
非常感谢。
解决方案
使用 os.path.isfile() 检查 f 是不是一个文件。
for f in os.listdir(dir_path):
if os.path.isfile(f):
...
推荐阅读
- java - 如何从不同的活动中获取 RadioGroup 的价值
- swift4 - 使用 Codable 将 JSON 转换为 Swift 对象
- python - 执行 windows shell 命令并处理输出变量
- c++ - 遇到 c++ 代码“#define ELEMENT(TYPE, FIELD)”
- perl - 在 Continue 块中使用 For 循环中声明的词法变量
- java - Sin taylor 级数递归逼近
- c++ - C++ 程序的退出状态 -1
- javascript - 使用 TMDb API 的 JSON 输入意外结束
- yii2 - Yii2 解析记录器消息
- mercurial - 本地中央 Mercurial 存储库的离线同步