open()默认使用哪个目录? [英] what directory does open() use by default?

查看:125
本文介绍了open()默认使用哪个目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

for line in open('some.txt'):

,表示找不到该文件.我的文件与python程序的方向相同.怎么了?我以为它检查的目录是

and it's saying the file is not found. I have the file in the same direction as my python program. what's wrong? I thought it checked the directory to be

解决方案:我使用了os.listdir(),发现我的文件实际上名为some.txt.txt

SOLUTION: I used os.listdir() and found out my file was actually named some.txt.txt

推荐答案

相对路径是从当前工作目录中解析的.

Relative paths are resolved from the current working directory.

例如,假设我具有以下目录结构:

For example, let's say I have this directory structure:

/home/joe
├── data
│   └── numbers.txt
└── programs
    └── process.py

如果我在主目录(/home/joe)中,则可以通过programs/process.py引用Python脚本,并通过data/numbers.txt引用数据文件.您还可以选择使用绝对路径,例如/home/joe/programs/process.py/home/joe/data/numbers.txt.

If I were in my home directory (/home/joe), then I could reference the Python script by programs/process.py and the data file by data/numbers.txt. You could also opt to use absolute paths, e.g., /home/joe/programs/process.py and /home/joe/data/numbers.txt.

您可以使用..访问父目录.例如,如果我在programs目录中,并且想访问numbers.txt,则可以使用../data/numbers.txt(或绝对路径,如前).

You can access the parent directory with ... For example, if I were in the programs directory and I wanted to access numbers.txt, I could use ../data/numbers.txt (or an absolute path, as before).

您的脚本可以使用 os.getcwd 来检查其当前工作目录. a>并使用 os.chdir 更改当前工作目录.

Your script can examine its current working directory using os.getcwd and change the current working directory using os.chdir.

要注意的关键一点是,尽管当前工作目录和目录中的脚本位于 中,但该脚本可能是相同的,但不一定是这种情况.如果要访问与脚本相同目录中的文件,而不管当前工作目录是什么,可以将以下内容链接在一起:

The critical thing to note is that while the current working directory and directory the script is in may be the same, that is not necessarily the case. If you want to access a file in the same directory as the script regardless of what the current working directory is, you can chain a few things together:

  1. __file__是预定义的全局变量,与提供给Python可执行文件的脚本路径相对应.
  2. os.path.dirname 可让您获得那个目录.
  3. os.path.join 可让您结合该目录以及您要访问的文件的名称.
  1. __file__ is a predefined global variable corresponding to the script's path as it was provided to the Python executable.
  2. os.path.dirname lets you get the directory from that.
  3. os.path.join lets you combine that directory and the name of the file you want to access.

这篇关于open()默认使用哪个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆