我的当前工作目录是~/Desktop/Development/Python/djcode/mysite,我想打开桌面上的一个文件。如何使用不同目录下的语法打开文件?(比如如果文件在当前工作目录下,我可以使用 open('file') 来打开)。谢谢。
试试这个:
>>> import os
>>> path = os.path.expanduser('~/Desktop/foo.txt')
>>> open(path, 'r')
<open file '/home/pat/Desktop/foo.txt', mode 'r' at 0x7f0455af0db0>
使用路径,可以是绝对路径:
myfile = open('/path/to/myfile.ext')
或相对路径:
myfile = open('../../../../myfile.ext')
根据情况使用更合适的方法。您可以使用os.path.expanduser()函数来扩展路径中的~
部分。
with open('c:\absolutepath\file') as f:
content = f.read()
使用相对路径?../../../../file