使用Python重命名和移动文件 [英] Rename and move file with Python

查看:433
本文介绍了使用Python重命名和移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有python脚本,可将文件夹中的现有文件名与参考表进行比较,然后确定是否需要重命名.

I have python script that compares existing file names in a folder to a reference table and then determines if it needs to be renamed or not.

遍历每个文件名:

'oldname' = the current file name

'newname' = what it needs to be renamed to

我想重命名文件并将其移动到新文件夹".. \ renamedfiles"

I want rename the file and move it to a new folder "..\renamedfiles"

我可以在遍历循环的同时进行重命名和移动吗?

Can I do the rename and the move at the same time as it iterates through the loop?

更新: 抱歉,总体来说我很绿色,但这似乎很基本. shutil.move 正是我需要的-我只是不知道要查找它.下面的测试成功.现在将其工作到脚本中.

Update: Apologies, I'm fairly green with scrpting in general but this appears to be pretty basic. shutil.move is exactly what I needed THANKS- I just didn't know to look for it. Successful test below. Now to work it into the script.

import shutil
os.chdir('C:\Users\me\Desktop\New folder')
renFolder= 'Renamed'
oldname = 'Test.txt'
newname= 'renTest.txt'
shutil.move(oldname, renFolder+'/'+newname)

如果源位置和目标位置位于不同的分区/驱动器/设备上,则

推荐答案

os.rename(和os.replace)将不起作用.在这种情况下,您需要使用shutil.move ,它将在可能的情况下使用原子重命名,如果目标不在同一文件系统上,则回退以复制然后删除.在同一操作中同时移动和重命名非常高兴;无论如何,操作都是一样的.

os.rename (and os.replace) won't work if the source and target locations are on different partitions/drives/devices. If that's the case, you need to use shutil.move, which will use atomic renaming if possible, and fallback to copy-then-delete if the destination is not on the same file system. It's perfectly happy to both move and rename in the same operation; the operation is the same regardless.

这篇关于使用Python重命名和移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆