Open File in Another Directory (Python)

后端 未结 4 863
抹茶落季
抹茶落季 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:34

    If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

    path = 'C:\\Users\\Username\\Path\\To\\File'
    
    with open(path, 'w') as f:
        f.write(data)
    

    Edit:

    Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

    import os
    
    cur_path = os.path.dirname(__file__)
    
    new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
    with open(new_path, 'w') as f:
        f.write(data)
    

    Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

提交回复
热议问题