简体   繁体   English

Python打开文件 - 你不需要文件的完整路径吗?

[英]Python open file- dont you need full path to the file?

Every example I see about opening a file in Python has something like this: 我在Python中打开文件的每个例子都是这样的:

myFile = open('somefilenamehere', 'r')

It never works for me when I just type the file name...you should always put full directory path where that file is 当我输入文件名时,它永远不适合我...你应该总是把完整的目录路径放在那个文件的位置

myFile = open('C:\\blah\\blah\\somefilenamehere', 'r')

Does it work for someone? 它对某人有用吗? I mean just putting the name of the file? 我的意思是只是把文件的名称?

That has more to do with the process working directory than with where the script is. 这与进程工作目录有关 ,而与脚本的位置有关。 For example, you have a script called cat.py like: 例如,您有一个名为cat.py的脚本,如:

import sys
with open(sys.argv[1]) as fp:
    print fp.read()

and then you do: 然后你做:

$ cd /tmp
$ echo 12345 > test.txt
$ python /path/to/cat.py test.txt
12345

This will work as expected regardless of the script location, since the working directory is /tmp and the script doesn't change it. 无论脚本位置如何,这都将按预期工作,因为工作目录是/tmp且脚本不会更改它。

It's a relative path. 这是一条相对的道路。 So, you can put only filename if you run script in the same directory. 因此,如果在同一目录中运行脚本,则只能放置文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM