0

I am new to Python and I need to write a simple data processing script. I made a very simple script that just takes a file name from the program arguments from the command line and just prints the value of the first argument:

import sys

if __name__ == '__main__':

    fileName = sys.argv[1]

    print "File name is %s" % fileName

Then I run the program: myProgram.py ~/datadir/file.txt

Since nothing tells python that the argument is actually a path, I am surprise that infers it itself and resolves the ~ into a fully qualified path and the program outputs:

File name is /Users/<my_username>/datadir/file.txt

However, I am able to work around that by wrapping the command line argument in quotes:

myProgram.py "~/datadir/file.txt"
File name is ~/datadir/file.txt

Since I am in the process of learning Python, I was wondering is someone could explain what drives this implicit resolution. E.g. does it automatically assume anything starting with ~ is a path?

4

2 回答 2

7

不是 Python 将~字符解析到主目录,而是你的 shell;由于您使用的是 Mac OS X,因此很可能是bash. 在文件名周围添加引号将阻止 shell 解析~字符,因此 Python 会“按原样”获取它。

顺便说一句,Python 模块中的expanduser函数os.path也可以解析~到用户的主目录。

于 2013-08-21T21:25:37.780 回答
2

~符号是 Unix 和类 Unix 系统中的约定,它与 Python 无关。这意味着:相对于当前用户的主目录启动此路径。

于 2013-08-21T21:25:33.623 回答