开发者

renaming file prefixes and filetypes

开发者 https://www.devze.com 2023-02-27 06:16 出处:网络
In python 2.7, how would I go about renaming any .bat files in my current directory to a file called 1.txt?

In python 2.7, how would I go about renaming any .bat files in my current directory to a file called 1.txt?

(ex) If these are the files in my directory: [test.txt, abc.exe, dkckx.bat, 123.vbs], how could I rena开发者_运维百科me the dkckx.bat to 1.txt?

thx in advance.


Check the python documentation for the rename function.

And may be glob will be helpful too.


os.path has everything you'd need for filename manipulation. glob can search for files:

import os, glob

i = 1

for f in glob.glob('*'):
  if os.path.splitext(os.path.split(f)[-1])[-1].lower() == '.bat':
    os.rename(f, '{0}.txt'.format(i)
    i += 1

No guarantees, but I think this above script should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消