Filter return results printed in text file python

95 views Asked by At

Using this code:

from pysnap import Snapchat
from pprint import pprint

s = Snapchat()

username = raw_input('Enter your username: ')
password = raw_input('Enter your password: ')
s.login(username, password)
friends = s.get_friends()

newfile = open("newfile.txt", "a")
pprint(friends, newfile)

It prints the return / results of get_friends() Which is great, almost exactly what I want.

But.

The results are like this:

{u'can_see_custom_stories': True,
  u'direction': u'OUTGOING',
  u'display': u'',
  u'name': u'a7twini', #a7twini being the username here
  u'type': 0},

The ONLY thing I want it to display is:

a7twini
<nextusername>
<nextusername>
etc..

Is there a way to "filter" these results? Making sure only the name ends up in the text file?

I hope someone can help me, thanks!

Edit: someone asked for the get_friends() function

def get_friends(self):
    """Get friends
    Returns a list of friends.
    """
    return self.get_updates().get('friends', [])
1

There are 1 answers

6
DanielGibbs On BEST ANSWER

You can just print the name entry for each friend. Assuming friends is a list:

for friend in friends:
    newfile.write(friend[u'name'] + "\n")

Or you could use list comprehension:

newfile.writelines([friend[u'name'] + "\n" for friend in friends])