Ashu Ashu - 1 month ago 10
Bash Question

Read name of Package attribute and rename the current file with name of the package

We have a requirement in python, where we have 50 txt files as below in a folder; what we need here is take out the name( of the package attribute and rename the file (ex:Paytm.txt) to packageName.txt( for all the files in the given folder

Example : Paytm.txt
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<manifest xmlns:android="" package="">

I appreciate all your help.

Answer Source

There are two approaches you could take to extract the package name:

  1. Parse the file as an XML file, and then extract the package name:

    def extract_package_name(filename):
        tree = ET.parse('Paytm.txt')
        root = tree.getroot()
        return root.attrib["package"]
  2. Use regular expressions

    def extract_package_name(filename):
        with open(filename, 'r') as manifest_file:
            for line in manifest_file:
                mo = re.match('pattern="(.*)">', line)
                if mo:

Renaming the file should be easy:

def rename_file(file):
    package_name = extract_package_name(file)
    os.rename(file, package_name + ".txt")