2009-07-24 5 views
0

파이썬에서 특정 폴더 및 모든 하위 폴더의 파일을 반환해야하는 함수를 작성했습니다.특정 폴더에서만 파일을 반환합니다.

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

을하지만 fileName 당신은 예를 들어 전달할 수 있습니다 : 파일 이름은 함수 매개 변수에서 가져옵니다. "..\\Windows\\passwords.txt "또는 점에 대한 일부 유니 코드 문자

그것을 해결하는 방법에 어떤 정규식 어쩌면

+0

뭘 하시겠습니까? filename으로 주어진 문자열이 유효한 파일 이름인지 확인하십시오. – luc

+0

그 프로그램이 단지 하나의 폴더 (및 하위 폴더)에서 파일을 반환 할 수 있고 아무도 ex와 parametr을 줄 수 없도록하고 싶습니다. ".."하고 서버의 모든 파일을 읽습니다. –

+0

참조 : http://stackoverflow.com/questions/120656/directory-listing-in-python, http://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the -current-directory –

답변

4

를? os.path.normpath 함수는 ".."와 같은 것을 해결하는 주어진 경로 py를 정규화합니다. 그런 다음 결과 경로가 예상 디렉토리에 있는지 확인할 수 있습니다 :

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") 
1

어떨까요 :

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)) 
+0

창에서 : >>> r '../../ AUTOEXEC.BAT'.split (os.path.sep) [- 1]'결과 :'../../AUTOEXEC .BAT''. – SilentGhost

+0

원시 텍스트 분할 사용시 예상대로 작동하지 않을 수도 있습니다. 나는 내 대답을 업데이 트했습니다, 고마워. –

관련 문제