python-twitterでフレンドリストをファイルに保存する
課題の英語に追われるだけで1日が終わるのはまっぴらゴメンだったので、少しだけPythonで遊びました。
これからpython-twitterで色々遊ぶのに、フレンドリスト*1をファイルに保存しておくと便利なので、さくっとファイルに保存するコードを書きました。
python-twitterのGetFriends()で100人以上取得するで取得したリストをファイルに書き込みます!
#!/usr/bin/env # -*- coding: utf-8 -*- """ getfriends.py Twitterのフレンドリストを取得し、ファイルに保存する """ import codecs import twitter def getfriends(filename="friends.txt"): api = twitter.TwitterApi("ユーザー名", "パスワード") users = api.GetFriends() f = codecs.open(filename, "w", "utf-8") for user in users: f.write(user.name + "\n") f.close() print "Succeeded to make %s" % filename if __name__ == "__main__": getfriends()
codecsモジュールを使わないと、ユニコード文字列の書き込みやらなんやらができないみたい。
(デフォルトで)friends.txtにお友達の名前を1行にひとりずつ書き込みます。
こんな風にモジュールとして使うこともできます!
>>> from getfriends import getfriends >>> getfriends("myfriends.txt") Getting friends: 1 - 100 Getting friends: 101 - 200 Succeeded to make myfriends.txt
ファイル名も指定できて便利ですね!
*1:フォローしてる人のリスト。following