2

I am working on a project where I will need to potentially open and read a textfile either on a local server or remotely (via url). Is there a python function that works like php's :

file_get_contents()

that can do this? right now I have:

def get_data_from_file(path):

    for i, line in enumerate(open(path)):
        .....

I would like to pass in a path either locally or remotely.

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • What do you mean by a textfile "on a local server" or "remotely"? If it's just an SMB, NFS, AFP, etc. share, you just open it; nothing above the level of the filesystem cares where the share comes from. If it's, say, an FTP or HTTP URL, or a file that you can access by `ssh`ing into a system and then reading it, or something different… well, then the answer depends on which of those it is. – abarnert Oct 08 '14 at 19:49
  • 1
    Shouldn't be too hard to roll your own . . . `try` to open the file. If you fail, then `try` to use `urllib2` to open the url. Then return the file object for the caller to use how they wish (or raise a suitable exception neither succeeds). . . – mgilson Oct 08 '14 at 19:49
  • possible duplicate of [How do I read a text file into a string variable in Python](http://stackoverflow.com/questions/8369219/how-do-i-read-a-text-file-into-a-string-variable-in-python) – will Oct 08 '14 at 19:50
  • sorry, the remote textfile is available via a url eg http://stackoverflow.com/mytextfile.txt . I'm just wondering if there is a unified command that can do both in python like file_get_contents() in php – user1592380 Oct 08 '14 at 19:53
  • 1
    If it's _always_ a URL (including a file: URL for whatever "local server" means), you can just always use `urllib` in the first place. – abarnert Oct 08 '14 at 19:54

1 Answers1

1

You could try:

def file_get_contents(path):
  try:
    urllib.urlretrieve(path, filename=path)
  except:
    print 'not a page'

  if os.path.exists(path):
     with open(path, r) as file:
        data = file.read()
        print data
  else:
    print 'no such file'
Vizjerei
  • 1,000
  • 8
  • 15