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(com.paytm.mShop.android.install) of the package attribute and rename the file (ex:Paytm.txt) to packageName.txt(com.paytm.mShop.android.install.txt) for all the files in the given folder

Example : Paytm.txt
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.paytm.android.install">
.
.
..
</manifest>


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:
                    return mo.group(1)
    

Renaming the file should be easy:

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