我正在尝试编写我的第一个脚本。 我一直在阅读有关 python 的文章,但我很股票。
我正在尝试编写一个脚本来重命名特定文件夹中的所有文件名。 这是我到目前为止所拥有的:
import os
files = os.listdir('files_to_Change')
print (files)
从文件夹中获取所有文件名:
for i in files:
if i == ".DS_Store":
p = files.index(".DS_Store")
del files[p]
如果 mac 不可见文件存在,请从列表中删除(这里可能是一个错误)。
for i in files:
oldName = i
fileName, fileExtension = os.path.splitext(i)
print (oldName)
print (fileName)
os.rename(oldName,fileName)
这是我的库存,我收到此错误:
输出:
FileNotFoundError: [Errno 2] No such file or directory: 'File.1'
在上面的部分中,我只是删除了文件扩展名,但这只是开始。 我还尝试用空格替换每个点并使每个单词的第一个字母大写。
有人能指出我正确的方向吗?
非常感谢
最佳答案
在您的示例中,当您获取 files_to_Change
目录中的文件列表时,您将获得不带目录名的文件名:
>>> files = os.listdir('test_folder')
>>> print files[0]
.com.apple.timemachine.supported
因此,为了从目录树中的任何位置获取该文件的完整路径,您应该将目录名称 (files_to_Change
) 与文件名连接起来:
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中批量重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482844/