0

I am having some trouble figuring out how to split a string in a text file and separate the strings into separate files

Within the text file I have the following:

package:/system/app/CustomLocale/CustomLocale.apk=com.android.customlocale2
package:/system/app/Gallery2/Gallery2.apk=com.android.gallery3d
package:/system/app/Calendar/Calendar.apk=com.android.calendar

And I have the following code:

import os

os.system("adb shell pm list packages -f > apps.txt")

f = open('apps.txt',"r")
lines = f.readlines()
for line in lines:
    for word in line.split():
        #print(word)
        if word.startswith('.apk'):
            print(word)

Now I understand how to split each line up indivdually and pipe them into a file however i would like to implement a way to split the first part of the string which is "package:/system/app/CustomLocale/CustomLocale" from the second part which is ".apk=com.android.calendar". How would I start to implement this. Any help would be greatly appreciated.

Janechen
  • 3
  • 1

3 Answers3

1

Regex is your best friend for cases like this in general. For this particular case, use str.split([sep[, maxsplit]]) parameters to your advantage.

line.split('.', 1)
['package:/system/app/CustomLocale/CustomLocale','apk=com.android.customlocale2']

line.split('.apk=', 1)
['package:/system/app/CustomLocale/CustomLocale', 'com.android.customlocale2']

In this way, you can split the whole string on whatever you need, limit the split to however many breaks you want to make, and then use that however you need.

0

First, I think this is what you need: In Python, how do I split a string and keep the separators?

And, for this case,

import re

f = open('apps.txt',"r")
lines = f.readlines()
for line in lines:
    ret = re.split('(\.apk)', line)
    print ret[0]
    print ret[1]+ret[2]

The result is:

 package:/system/app/CustomLocale/CustomLocale
 .apk=com.android.customlocale2

package:/system/app/Gallery2/Gallery2
.apk=com.android.gallery3d

package:/system/app/Calendar/Calendar
.apk=com.android.calendar
Community
  • 1
  • 1
周耀阳
  • 41
  • 4
0

Here is one more solution.
output is written to out1.txt (string before .apk) and out2.txt (after and including .apk)

import os
out1 = open('out1.txt', 'w')
out2 = open('out2.txt', 'w')
f = open('sample.txt', 'r')
lines = f.readlines()
pat='.apk'
for line in lines:
    line=line.rstrip()
    x=line.split(pat,1)
    out1.write(x[0]) 
    out1.write('\n') 
    out2.write(pat)      
    out2.write(x[1])      
    out2.write('\n')      
out1.close()
out2.close()
f.close()
Ramamohan
  • 1
  • 1