Python method to get the suffix name of a file and to update the suffix name of a file in a directory in batches

  • 2020-04-02 14:22:25
  • OfStack

This article illustrates the python method of obtaining the suffix name of a file and batch updating the suffix name of a file in a directory. Share with you for your reference. The specific implementation method is as follows:

1. Get the suffix name of the file:

#!/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()
For example, ABC /ef.g.h, here we get h

2. Python finds a file instance that traverses the specified file path with the specified suffix:

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. Instance of file suffix in batch rename directory:
import os
def swap_extensions(dir, before, after):
    if before[:1] != '.': # If there is no suffix name in the argument '.' Then add
        before = '.' + before
    thelen = -len(before)
    if after[:1] != '.':
        after = '.' + after
    for path, subdir, 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 ending in.php under e:/py/test to.py
 
E: p y > 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 has helped you with your Python programming.


Related articles: