python批量命名文件_python在Mac中批量重命名文件

1586010002-jmsa.png

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]

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:

Output:

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?

Thanks so much

解决方案

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

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 ))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值