程序无法从arg中读取路径名."没有相应的文件和目录"

pat*_*ues 0 python

我有一个python脚本的新问题.当我尝试运行它将路径作为参数传递给程序时,它返回错误消息:" No such file or directory".该程序应该遍历路径名指定的目录,以查找文本文件并打印出前两行.

是的确,这是家庭作业,但我看了很多关于os和sys的内容,但仍然没有得到它.你们有些退伍军人能帮助新手吗?谢谢

    #!/usr/bin/python2.7
    #print2lines.py
    """
    program to find txt-files in directory and
    print out the first two lines
    """
    import sys, os

    if (len(sys.argv)>1):
        path = sys.argv[0]
        if os.path.exist(path):
            abspath = os.path.abspath(path):
                dirlist = os.listdir(abspath)
                for filename in dirlist:
                    if (filename.endswith(".txt")):
                        textfile = open(filename, 'r')
                        print filename + ": \n"
                        print textfile.readline(), "\n"
                        print textfile.readline() + "\n"

                    else:   
                        print "passed argument is not valid pathname"
    else:   
        print "You must pass path to directory as argument"
Run Code Online (Sandbox Code Playgroud)

Lev*_*von 5

与您的路径相关的问题是:

path = sys.argv[0]
Run Code Online (Sandbox Code Playgroud)

argv[0]指的是命令运行(通常是Python脚本的名称)..如果你想要第一个命令行参数,请使用索引1,而不是0.也就是说,

path = sys.argv[1]
Run Code Online (Sandbox Code Playgroud)

示例脚本tmp.py:

import sys, os
print sys.argv[0]
print sys.argv[1]
Run Code Online (Sandbox Code Playgroud)

并且:python tmp.py d:\users给出:

 tmp.py
 d:\users
Run Code Online (Sandbox Code Playgroud)

还有两个语法错误:

    if os.path.exist(path):  # the function is exists()  -- note the s at the end
        abspath = os.path.abspath(path):  # there should be no : here
Run Code Online (Sandbox Code Playgroud)