Skip to content

Instantly share code, notes, and snippets.

@lioneldp
Created September 30, 2013 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lioneldp/6761743 to your computer and use it in GitHub Desktop.
Save lioneldp/6761743 to your computer and use it in GitHub Desktop.
Instead of working with python at the desktop, I often use pythonista on my ipad to work through coursework for coursera. I need to access separate text files to accomplish certain exercises, which is no problem usually, except when it comes to text files locked behind secure password protected websites such as dropbox. How do I get through the …
from dropbox import client, rest, session
import urllib
import webbrowser
import re
from dropboxlogin import get_client
dropbox_client = get_client()
apples_file = dropbox_client.get_file('iA Write/All because I said "apple.txt').read()
def lines_startswith(file, letter):
""" (file open for reading, str) -> list of str
Return the list of lines from file that begin with letter. The lines should have the
newline removed.
Precondition: len(letter) == 1
"""
matches = []
for line in file:
if line.startswith(letter):
matches.append(line.rstrip('\n'))
print matches
lines_startswith(apples_file, 'A')
@cclauss
Copy link

cclauss commented Sep 30, 2013

My sense is that you should rename apples_file to apples_file_content or apples_file_text. The call to .read() at the end of that line should mean that you now have the content (the text) of the file instead of a file handle. The way to test my assumption is to put the line "print(apples_file)" just after your call to dropbox_client.get_file(). If it prints out the contents of your file then my assumption is correct.

If you already have the content of the file then you could write:

def lines_startswith(text, letter):
matches = []
for line in text.splitlines():
if line.startswith(letter):
matches.append(line.rstrip('\n'))
print matches
print('\n'.join(matches))

or in one line...
def lines_startswith_2(text, letter):
print([x for x in text.splitlines() if x[0] == letter])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment