Open File in Another Directory (Python)

后端 未结 4 855
抹茶落季
抹茶落季 2020-12-08 02:56

I\'ve always been sort of confused on the subject of directory traversal in Python, and have a situation I\'m curious about: I have a file that I want to access in a directo

4条回答
  •  囚心锁ツ
    2020-12-08 03:26

    import os
    import os.path
    import shutil
    

    You find your current directory:

    d = os.getcwd() #Gets the current working directory
    

    Then you change one directory up:

    os.chdir("..") #Go up one directory from working directory
    

    Then you can get a tupple/list of all the directories, for one directory up:

    o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple
    

    Then you can search the tuple for the directory you want and open the file in that directory:

    for item in o:
        if os.path.exists(item + '\\testfile.txt'):
        file = item + '\\testfile.txt'
    

    Then you can do stuf with the full file path 'file'

提交回复
热议问题