Python 无法保存名称前有斜杠的文件
Python Unable to save file with slash in front of name
with open('/tests/testDict.pickle','wb') as fp: print 'to terminal'
上面的内容有什么问题,让我抓狂并给出了以下内容:
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-17-fe5a4a9f361c> in <module>()
----> 1 with open('/tests/testDict.pickle','wb') as fp: print 'to terminal'
IOError: [Errno 2] No such file or directory: '/tests/testDict.pickle'
如果前面没有斜杠,我会得到:
with open('tests/testDict.pickle','wb') as fp: print 'to terminal'
to terminal
我在 OS X:
中有以下目录结构
$ ls
cp1.py cp1_pdftest.jpg random/ tests/
当你有前导斜杠时,它表示绝对路径。也就是说,除非您在系统的根目录 (/
) 中有一个名为 'tests' 的目录,否则这将不起作用。
/
只是根目录,也许你应该试试./
"/tests/"
上的前导斜杠强制路径为绝对路径,即使您正在执行
os.path.join(os.getcwd(), "/tests/")
所以你需要做
os.path.join(os.getcwd(), "tests/")
来自 os.path.join 文档:
os.path.join(path, *paths)
Join one or more path components intelligently. The return value is
the concatenation of path
and any members of *paths
with exactly one
directory separator (os.sep
) following each non-empty part except
the last, meaning that the result will only end in a separator if the
last part is empty. If a component is an absolute path, all previous
components are thrown away and joining continues from the absolute
path component.
with open('/tests/testDict.pickle','wb') as fp: print 'to terminal'
上面的内容有什么问题,让我抓狂并给出了以下内容:
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-17-fe5a4a9f361c> in <module>()
----> 1 with open('/tests/testDict.pickle','wb') as fp: print 'to terminal'
IOError: [Errno 2] No such file or directory: '/tests/testDict.pickle'
如果前面没有斜杠,我会得到:
with open('tests/testDict.pickle','wb') as fp: print 'to terminal'
to terminal
我在 OS X:
中有以下目录结构$ ls
cp1.py cp1_pdftest.jpg random/ tests/
当你有前导斜杠时,它表示绝对路径。也就是说,除非您在系统的根目录 (/
) 中有一个名为 'tests' 的目录,否则这将不起作用。
/
只是根目录,也许你应该试试./
"/tests/"
上的前导斜杠强制路径为绝对路径,即使您正在执行
os.path.join(os.getcwd(), "/tests/")
所以你需要做
os.path.join(os.getcwd(), "tests/")
来自 os.path.join 文档:
os.path.join(path, *paths)
Join one or more path components intelligently. The return value is the concatenation of
path
and any members of*paths
with exactly one directory separator (os.sep
) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.