python 复制、移动文件到指定目录并修改名字

基本思路:

1、确定指定目录

2、判断指定目录是否存在,如果不存在就新建该目录

3、修改新的文件名

4、复制图片到指定位置,如果需要移动采用

shutil.move(origin_path, new_file_name)
import os
import shutil
base_dir = os.path.dirname(__file__)   # 获取当前文件目录
outfile = 'try_file'
path = os.path.join(base_dir, outfile) # path是需要把文件复制到的指定位置
# 我这儿达到的目的是:在py脚本的文件夹下新建try_file文件夹,并把图片改名保存到try_file文件下
# path也可以写成
# path = r'D:\try_file'
if os.path.exists(path):
    pass
else:
    os.mkdir(path)
new_file_name = r'%s\1___%s_%s_%s_%s.jpg' % (path, '我的', '妈呀', "hahaha", 123)  # 文件新名字
origin_path = r'D:\111_1231_haha.jpg'    # 原始文件完整目录
shutil.copyfile(origin_path, new_file_name)

shutil的官方使用文档:https://docs.python.org/3.6/library/shutil.html

# 复制文件:
shutil.copyfile("oldfile", "newfile")  # oldfile和newfile都只能是文件
# 复制文件夹:
shutil.copytree(r"D:\stuy", r"D:\newfile")  # olddir和newdir都只能是目录,且newdir必须不存在
# 重命名文件(目录)
os.rename(r"D:\newfile", r"D:\newfile1")  # 文件或目录都是使用这条命令
# 移动文件(目录)
shutil.move(r"D:\test", r"D:\test1")
shutil.move(r"D:\1___我的_妈呀_hahaha_123.jpg", r"D:\test1\111_1231_haha.jpg") #test1文件夹必须存在

python错误——SyntaxError: EOL while scanning string literal

python中,如果你的字符串最后一位是斜杠(slash)字符,那么即使字符串前面加了r表示regular的普通字符串,也是无法通过编译的,也是会导致SyntaxError的。

比如这样:r'D:\stuy1\'

解决方法:去掉最后的\

猜你喜欢

转载自blog.csdn.net/qingfengxd1/article/details/87345165
今日推荐