Tag Archives: Python

How to Tweet From Python

Step one

Download and install twython, using pip. I’m using python 3 so I typed the command

sudo pip3 install twython

 

 

Step 2

Go to apps.twitter.com and create an account using your Twitter username and password.

 

Step 3

Click ‘Create New App’

Step 4

Fill in the mandatory fields and click next, if you don’t have a website just pop in a placeholder.

 

Step 5

Once your app is created you will now will be brought through to a new page, click ‘Key and Access Tokens’.

 

Step 6

Take note of the Consumer Key (API Key) and Consumer Secret (API Secret)

 

Step 7

You will need to create an access token.

 

 

Step 8

You should now see your access tokens, take note of these also.

 

Step 9

Open up your favorite text editor, I’m using Idle, and enter the following:

from twython import Twython

 

APP_KEY = ‘YOUR_KEY_GOES_HERE’
APP_SECRET = ‘YOUR_SECRET_GOES_HERE’
OAUTH_TOKEN = ‘YOUR_TOKEN_GOES_HERE’
OAUTH_TOKEN_SECRET = ‘YOUR_TOKEN_SECRET_GOES_HERE’

 

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status=’this is a test tweet from a python script!’)

 

Step 7

Now run your script, if using Idle, you can do this by pressing F5.

 

Step 8

Check Twitter to make sure your tweet has sent.

Python: Searching CSVs and exporting rows based on string macthes

Recently I had a need to search through a CSV log file, that was thousands of rows long and find certain names that existed in the log file and copy these rows to another CSV. I had to do this for dozens of names, each of which could have dozens of matches. Instead of searching for each of these names and copying the rows to another CSV file (which would have taken hours!) I decided to write a script that would do this task in a matter of seconds:

The script below opens one CSV; the file which you want to search. It then saves a new file with the results. There is a list at the start of of the program called people. You can add your own strings here which you are looking for in your CSV file:

 

The Script


import csv

people = [‘Joe Bloggs’, ‘Tim O Reilly’, ‘Mary Bloggs’]

with open(‘users.csv’) as oldfile, open(‘report.csv’, ‘w’) as newfile:
for line in oldfile:
if any(people in line for people in people):
newfile.write(line)

Example

Say we have a log file with 1000s of rows and we want to find all activity for the users Joe Bloggs, Tim O’Reilly and Mary Bloggs. The log file may look something like this:

User Action
Joe Bloggs Login
Mary Burke login
Darren O Neill Updated post
Joe Bloggs Updated post
Tim O Reilly login
Mary Bloggs login

Now if we run the script we can see the file returned only contains the users we are interested in.

Joe Bloggs Login
Joe Bloggs Updated post
Tim O Reilly login
Mary Bloggs login