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