Python get file suffix name and batch update file suffix name instance in directory

Source: Internet
Author: User

Get file suffix name

The code is as follows Copy Code

#!/usr/bin/python

Import OS

Dict = {}
For D, FD, FL in Os.walk ('/home/ahda/program/'):
For F in FL:
Sufix = Os.path.splitext (f) [1][1:]
If Dict.has_key (Sufix):
Dict[sufix] + + 1
Else
Dict[sufix] = 1

For item in Dict.items ():
Print '%s:%s '% item

The key here is Os.path.splitext ()
This is a different place from the upstairs. such as Abc/ef.g.h
The suffix from upstairs will be g.h.
And mine is H.

Instance

Python lookup traverses a file with the specified suffix name under the specified file path

The code is as follows Copy Code

Import OS
Import Sys
Import Os.path

For Dirpath, Dirnames, filenames in Os.walk (Startdir):
For filename in filenames:
If Os.path.splitext (filename) [1] = = ' txt ':
filepath = Os.path.join (dirpath, filename)
#print ("File:" + filepath)
Input_file = open (filepath)
Text = Input_file.read ()
Input_file.close ()

output_file = open (filepath, ' W ')
Output_file.write (text)
Output_file.close ()

Instance

#批量重命名目录中的文件后缀

The code is as follows Copy Code
Import OS
Def swap_extensions (dir, before, after):
If before[:1]!= '. ': #如果参数中的后缀名没有 '. ' Then add
Before = '. ' + Before
Thelen =-len (before)
If after[:1]!= '. ':
after = '. ' +
For path, subdir, the files in Os.walk (dir):
For oldfile in Files:
If Oldfile[thelen:] = = before:
Oldfile = Os.path.join (path, oldfile)
NewFile = Oldfile[:thelen] + after
Os.rename (Oldfile, NewFile)
Print Oldfile + ' changed to ' + NewFile
if __name__ = = ' __main__ ':
Import Sys
If Len (SYS.ARGV)!= 4:
print ' Usage:swap_extension.py RootDir before after '
Sys.exit (1)
Swap_extensions (Sys.argv[1], sys.argv[2], sys.argv[3])

Example: Rename the file at the end of Php e:/py/test to. py


E:py>python_cook e:/py/test. php. py

E:/py/testtest.php changed to e:/py/testtest.py

E:/py/test1.php changed to e:/py/test1.py

E:/py/test2.php changed to e:/py/test2.py

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.