python Python首先在哪里寻找文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1668594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:50:34  来源:igfitidea点击:

Where does Python first look for files?

pythonfile

提问by Federer

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?

我正在尝试学习如何在 Python 中解析 .txt 文件。这导致我打开解释器(终端> python)并四处玩耍。但是,我似乎无法指定正确的路径。Python 首先看哪里?

This is my first step:

这是我的第一步:

    f = open("/Desktop/temp/myfile.txt","file1")

This blatantly doesn't work. Can anyone advise?

这公然行不通。任何人都可以建议吗?

回答by Dave Webb

That doesn't work as you've got the wrong syntax for open.

这不起作用,因为您对open.

At the interpreter prompt try this:

在解释器提示下试试这个:

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.

So the second argument is the open mode. A quick check of the documentationand we try this instead:

所以第二个参数是开放模式。 快速检查文档,我们尝试这样做:

f = open("/Desktop/temp/myfile.txt","r")

回答by Bartek

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.

Python 会查找您告诉它打开文件的位置。如果您在 /home/malcmcmul 中打开解释器,那么这将是活动目录。

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.

如果您指定路径,那就是它的外观。您确定 /Desktop/temp 是有效路径吗?我不知道 /Desktop 是这样的根文件夹的许多设置。

Some examples:

一些例子:

  • If I have a file: /home/bartek/file1.txt

  • And I type pythonto 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")

  • 如果我有一个文件:/home/bartek/file1.txt

  • 我输入python以在目录中获取我的解释器/home/bartek/

  • 这将工作并获取 file1.txt ok: f = open("file1.txt", "r")

  • 这将不起作用:f = open("some_other_file.txt", "r")因为该文件位于某种类型的另一个目录中。

  • 只要我指定了正确的路径,这就会起作用: f = open("/home/media/a_real_file.txt", "r")

回答by Brent Newey

To begin with, the second argument is the permissions bit: "r" for read, "w" for write, "a" for append. "file1" shouldn't be there.

首先,第二个参数是权限位:“r”表示读取,“w”表示写入,“a”表示追加。“file1”不应该在那里。

回答by Abgan

Try:

尝试:

f = open('Desktop/temp/myfile.txt', 'r')

This will open file relatively to current directory. You can use '/Desktop/temp/myfile.txt'if you want to open file using absolute path. Second parameter to open function is mode (don't know what file1should mean in your example).

这将打开相对于当前目录的文件。您可以使用'/Desktop/temp/myfile.txt',如果你想使用绝对路径打开文件。open 函数的第二个参数是 mode (不知道file1在你的例子中应该是什么意思)。

And regarding the question - Python follows OS scheme - looks in current directory, and if looking for modules, looks in sys.pathafterwards. And if you want to open file from some subdirectory use os.path.join, like:

关于这个问题 - Python 遵循操作系统方案 - 在当前目录中查找,如果查找模块,则在sys.path之后查找。如果您想从某个子目录打开文件,请使用 os.path.join,例如:

import os
f = open(os.path.join('Desktop', 'temp', 'myfile.txt'), 'r')

Then you're safe from the mess with '/' and '\'.

然后你就可以避免使用 '/' 和 '\' 了。

And see docs for built-in open functionfor more information about the way to use open function.

有关使用 open 函数的方式的更多信息,请参阅内置 open 函数的文档。

回答by Flasknoobie

Just enter your file name and there is your data.....what it does?---->If path exists checks it is a file or not and then opens and read

只需输入您的文件名,就有您的数据.....它有什么作用?---->如果路径存在检查它是否是一个文件,然后打开并读取

import os
fn=input("enter a filename: ")
if os.path.exists(fn):
    if os.path.isfile(fn):
        with open(fn,"r") as x:
            data=x.read()
            print(data)
    else:
        print(fn,"is not a file: ")
else:
    print(fn,"file doesnt exist ")

回答by inspectorG4dget

This:

这:

import os
os.path

should tell you where python looks first. Of course, if you specify absolute paths (as you have), then this should not matter.

应该告诉你 python 首先看哪里。当然,如果您指定绝对路径(如您所愿),那么这应该无关紧要。

Also, as everyone else has said, your second argument in open is wrong. To find the proper way of doing it, try this code:

此外,正如其他人所说,您公开的第二个论点是错误的。要找到正确的方法,请尝试以下代码:

help(open)

回答by Shakujin

A minor potential issue that the original post does not have but, also make sure the file name argument uses '/' and not '\'. This tripped me up as the file inspector used the incorrect '/' in its location.

原始帖子没有的一个小潜在问题,但还要确保文件名参数使用“/”而不是“\”。这让我感到困惑,因为文件检查器在其位置使用了不正确的“/”。

'C:\Users\20\Documents\Projects\Python\test.csv' = Does not work

'C:\Users\20\Documents\Projects\Python\test.csv' = 不起作用

'C:/Users/20/Documents/Projects/Python/test.csv' = Works just fine

'C:/Users/20/Documents/Projects/Python/test.csv' = 工作正常