Ken*_*nyC 3 python operating-system rename
我有多个看起来像folder.0和的文件夹folder.1.每个文件夹内有一个文件('junk'),我想复制和重命名的.0或.1在它目前所在的文件夹名称的一部分.
这是我正在尝试做的事情:
inDirec = '/foobar'
outDirec = '/complete/foobar'
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
os.rename(file, iterator+file) # change name to include folder no.
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
Run Code Online (Sandbox Code Playgroud)
返回:
os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
我甚至不确定我应该使用os.rename.我只是想拉出来files == 'junk'并将它们复制到一个目录中,但它们都具有完全相同的名称.所以我真的只需要重命名它们,以便它们可以存在于同一目录中.有帮助吗?
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
it = iterator[-1] # iterator began with a '.'
shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
Run Code Online (Sandbox Code Playgroud)
您的问题是您的程序在启动时使用工作目录进行重命名操作.您需要提供完整的相对或绝对路径作为os.rename()的参数.
更换:
os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
Run Code Online (Sandbox Code Playgroud)
随着(如果你想移动):
os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))
Run Code Online (Sandbox Code Playgroud)
或者(如果你想复制):
shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))
Run Code Online (Sandbox Code Playgroud)
注意:目标目录应该已经存在,或者您将需要代码来创建它.