This example describes Python's method of getting file suffix names and the batch updating of file suffix names in the directory. Share to everyone for your reference. The implementation methods are as follows:
1. Get file suffix name:
Copy Code code as follows:
#!/usr/bin/python
Import os
Dict = {}
for D, FD, FL in Os.walk ('/h ome/ahda/program/'):
for F in FL:
& nbsp; Sufix = Os.path.splitext (f) [1][1:]
if Dict.has_key (sufix):
Dict[sufix] + = 1
Else:
Dict[sufix] = 1
for item in Dict.items ():
& nbsp; print '%s:%s '% Item
The key here is Os.path.splitext ()
Like Abc/ef.g.h, here's what we get here is H.
2. Python lookup traverses a file instance of the specified suffix name under the specified file path:
Copy Code code as follows:
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 ()
3. The file suffix instance in the batch renaming directory:
Copy Code code as follows:
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
I hope this article will help you with your Python programming.