Finding a file's directory address on a Mac

后端 未结 4 768
我在风中等你
我在风中等你 2021-02-04 09:22

I am working with a Macbook programming python. What I want to know is how I can access certain files using Python\'s file functions. A google search failed me.

For exam

相关标签:
4条回答
  • 2021-02-04 09:46
    f = open (r"/Users/USERNAME/Desktop/somedir/somefile.txt")
    

    or even better

    import os
    f = open (os.path.expanduser("~/Desktop/somedir/somefile.txt"))
    

    Because on bash (the default shell on Mac Os X) ~/ represents the user's home directory.

    0 讨论(0)
  • 2021-02-04 09:56

    If this is still an issue, I had the same problem and called Apple. I learned that the file I'd created was saved on iCloud. The Apple guy told me to save the file locally. I did that and the problem was solved.

    0 讨论(0)
  • 2021-02-04 10:02

    You're working on a Mac so paths like "a/b/c.text" are fine, but if you use Windows in the future, you'll have to change all the '/' to '\'. If you want to be more portable and platform-agnostic from the beginning, you better use the os.path.join operator:

    import os
    
    desktop = os.path.join(os.path.expanduser("~"), "Desktop")
    filePath = os.path.join(desktop, "somefile.txt")
    
    f = open(filePath)
    
    0 讨论(0)
  • 2021-02-04 10:07

    The desktop is just a subdirectory of the user’s home directory. Because the latter is not fixed, use something like os.path.expanduser to keep the code generic. For example, to read a file called somefile.txt that resides on the desktop, use

    import os
    f = open(os.path.expanduser("~/Desktop/somefile.txt"))
    

    If you want this to be portable across operating systems, you have to find out where the desktop directory is located on each system separately.

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