1

Pythonスクリプトに新しい問題があります。パスを引数としてプログラムに渡して実行しようとすると、エラー メッセージ " No such file or directory" が返されます。このプログラムは、パス名で指定されたディレクトリを反復処理してテキスト ファイルを検索し、最初の 2 行を出力することになっています。

はい、確かに宿題ですが、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"
4

2 に答える 2

5

パスに関連する問題は次のとおりです。

path = sys.argv[0]

argv[0]コマンド run (通常は Python スクリプトの名前) を参照します。最初のコマンド ライン引数が必要な場合は、 0ではなくインデックス1を使用します。すなわち、

path = sys.argv[1]

スクリプト例tmp.py:

import sys, os
print sys.argv[0]
print sys.argv[1]

そして:python tmp.py d:\users与える:

 tmp.py
 d:\users

また、2 つの構文エラー:

    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
于 2012-06-15T21:42:29.993 に答える