Python首先在哪里查找文件? [英] Where does Python first look for files?
问题描述
这是我的第一步:
f = open(/ Desktop / temp / myfile.txt,file1)
公然不工作。任何人都可以提出建议?
编辑:哦,是的,你的第二个参数是错误的。甚至没有注意到:)
Python看起来在哪里告诉它打开文件。如果你打开/ home / malcmcmul中的解释器,那么这将是活动目录。
如果指定了一个路径,那就是它的外观。你确定/ Desktop / temp是一个有效的路径吗?
一些例子:
-
如果我有一个文件:/home/bartek/file1.txt
-
c> python 让我的解释器在
/ home / bartek /
目录下 -
这将工作,并获取file1.txt确定:
f = open(file1.txt,r)
-
这是行不通的:
f = open(some_other_file.txt,r)
。
-
只要我指定了正确的路径,就可以工作:
f = open(/ home / media / a_real_file.txt ,r)
I'm trying to learn how to parse .txt files in Python. This has led me to opening the interpreter (terminal > python) and playing around. However, I can't seem to be able to specify the right path. Where does Python first look?
This is my first step:
f = open("/Desktop/temp/myfile.txt","file1")
This blatantly doesn't work. Can anyone advise?
Edit: Oh and yes, your second argument is wrong. Didn't even notice that :)
Python looks where you tell it to for file opening. If you open up the interpreter in /home/malcmcmul then that will be the active directory.
If you specify a path, that's where it looks. Are you sure /Desktop/temp is a valid path? I don't know of many setups where /Desktop is a root folder like that.
Some examples:
If I have a file: /home/bartek/file1.txt
And I type
python
to get my interpreter within the directory/home/bartek/
This will work and fetch file1.txt ok:
f = open("file1.txt", "r")
This will not work:
f = open("some_other_file.txt", "r")
as that file is in another directory of some sort.This will work as long as I specify the correct path:
f = open("/home/media/a_real_file.txt", "r")
这篇关于Python首先在哪里查找文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!