tags:

views:

75

answers:

2

Hello.

I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:

def ReturnFile(fileName)
  return open("C:\\folder\\" + fileName,"r")

But as fileName you can pass for example: "..\\Windows\\passwords.txt" or some unicode symbols for dots.

How to fix it? Some RegExp maybe?

+4  A: 

The os.path.normpath function normalizes a given path py resolving things like "..". Then you can check if the resulting path is in the expected directory:

def ReturnFile(fileName)
  norm = os.path.abspath("C:\\folder\\" + fileName)
  if not norm.startswith("C:\\folder\\"):
    raise Exception("Invalid filename specified")
  return open(norm,"r")
sth
+1  A: 

How about this:

import os

_BASE_PATH= "C:\\folder\\"

def return_file(file_name):
    "Return File Object from Base Path named `file_name`"
    os.path.normpath(file_name).split(os.path.sep)[-1]
    return(open(_BASE_PATH+file_name))
Martin P. Hellwig
On windows: `>>> r'../../AUTOEXEC.BAT'.split(os.path.sep)[-1]` Results in: `'../../AUTOEXEC.BAT'`.
SilentGhost
Yeah that is true, when using raw text split may not work as expected. I've updated my answer, thanks.
Martin P. Hellwig