Open File in Another Directory (Python)

后端 未结 4 856
抹茶落季
抹茶落季 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:21
    from pathlib import Path
    
    data_folder = Path("source_data/text_files/")
    file_to_open = data_folder / "raw_data.txt"
    
    f = open(file_to_open)
    print(f.read())
    
    0 讨论(0)
  • 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'

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 03:35

    Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.

    To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r in front of the string with your actual path.

    For example,

    from pathlib import Path
    
    dataFolder = Path(r'D:\Desktop dump\example.txt')
    

    Source: The easy way to deal with file paths on Windows, Mac and Linux

    (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

    0 讨论(0)
提交回复
热议问题