python在Mac中批量重命名文件 [英] python Batch Renames files in mac

查看:384
本文介绍了python在Mac中批量重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写我的第一个脚本. 我一直在阅读有关python的信息,但我有库存.

I'm trying to write my first script. I have been reading about python but I am stock.

我正在尝试编写一个脚本,该脚本将重命名特定文件夹中的所有文件名. 这是我到目前为止所拥有的:

I'm trying to write a script that will rename all the file names in a specific folder. this is what I have so far:

import os
files = os.listdir('files_to_Change')
print (files)

从文件夹中获取所有文件名:

Get all the file names from folder:

for i in files:
    if i == ".DS_Store":
        p = files.index(".DS_Store")
        del files[p]

如果存在mac看不见的文件,请从列表中删除(这里可能是一个错误).

If mac invisible file exists delete from list (maybe a mistake here).

for i in files:
    oldName = i
    fileName, fileExtension = os.path.splitext(i)
    print (oldName)
    print (fileName)
    os.rename(oldName,fileName)

这是我的库存,出现此错误:

This is where I am stock, I get this error:

输出:

FileNotFoundError: [Errno 2] No such file or directory: 'File.1'

在上面的部分中,我只是删除了文件扩展名,但这仅仅是个开始. 我还试图用空格替换每个点,并将每个单词的首字母大写.

On the above part I'm just removing the file extension, but that is only the beginning. I'm also trying to substitute every point by a space and make the first letter of every word a capital.

有人能指出我正确的方向吗?

Can anyone point me in the right direction?

非常感谢

推荐答案

在您的示例中,当您获得files_to_Change目录中的文件列表时,将获得不带目录名称的文件名:

In your example, when you get a list of files in a files_to_Change directory, you get file names without the directory name:

>>> files = os.listdir('test_folder')
>>> print files[0]
.com.apple.timemachine.supported

因此,为了从目录树中的任何位置获取该文件的完整路径,应将目录名(files_to_Change)与文件名连接起来:

So in order to get the full path to that file, from whereever you're in your directory tree, you should join the directory name (files_to_Change) with the file name:

import os
join = os.path.join

src = 'files_to_Change'
files = os.listdir( src )


for i in files:
    old = i
    new, ext = os.path.splitext ( old )
    os.rename( join( src, old ), join( src, fileName ))

这篇关于python在Mac中批量重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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