python - 如何将文件从一个目录移动到另一个目录?
问题描述
目录文件名应附加当前日期 (yyyy-mm-dd)
import shutil
import os
source = '/path/to/source_folder'
dest1 = '/path/to/dest_folder'
files = os.listdir(source)
for f in files:
shutil.move(source+f, dest1)
解决方案
这可能对您有所帮助。
import os
import datetime
import shutil
now = datetime.datetime.now()
path ='f:\\python\\testdir\\'
dest_folder='f:/python/testdir/copyfolder/'
files=[]
#check if destination folder exists if not create one
if os.path.exists(dest_folder):
#ignore nothing to do
pass
else:
print("not exits")
os.mkdir(dest_folder)
for r, d, f in os.walk(path):
for file in f:
# if '.txt' in file:
#print(os.path.join(r, file))
files.append(os.path.join(r, file))
for f in files:
print(f)
#extract the file name from the path
base_name=os.path.basename(f)
#extracting the file name and it's extension
file_name,ext=os.path.splitext(base_name)
#print(ext)
#file_name+='_'+now.strftime("%Y-%m-%d %H:%M")
#append the current time stamp and it's extension and move the file to new destination
shutil.copy2(f,'f:/python/testdir/copyfolder/'+file_name+'-'+now.strftime("%Y-%m-%d")+ext)
#print(file_name)
推荐阅读
- ios - 在 iOS swift 4.2 中更改根视图控制器时,状态栏突然隐藏
- snmp - Zabbix snmpv3 - items 不起作用,但 snmpwalk 可以
- ruby-on-rails - 如何在 mongodb 中使用 $type 查找记录?
- three.js - 在 1 个场景中使用 2 个网格 + 着色器材质,每个都有不同的片段着色器(three.js)
- javascript - Javascript函数仅在第二次点击时起作用
- python - 使用 pytorch 进行句子分类的多类(使用 nn.LSTM)
- video-streaming - 是否有允许设置身份验证标头的 html 视频播放器?
- java - com.fasterxml.jackson.databind.exc.InvalidDefinitionException 从 Spring 启动应用程序调用 Rest API 时
- pandas - 如果缺少列值,则将增量值替换为 pandas 数据框
- encryption - 像 Oracle JDK 中的 OpenJDK 7 GCM 支持?