program can't read path name from arg. “No such file or directory”
我对Python脚本有一个新的问题。当我试图运行它时,将路径作为参数传递给程序,它返回错误消息:"
是的,的确是家庭作业,但我已经看了很多关于OS和sys的书,但还是没有读到。你们中的一些老兵能帮个新手吗?谢谢
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #!/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 +": " print textfile.readline()," " print textfile.readline() +" " else: print"passed argument is not valid pathname" else: print"You must pass path to directory as argument" |
与您的路径相关的问题是:
1 | path = sys.argv[0] |
1 | path = sys.argv[1] |
脚本
1 2 3 | import sys, os print sys.argv[0] print sys.argv[1] |
和:
1 2 | tmp.py d:\users |
还有两个语法错误:
1 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 |
1 | os.listdir("test") #-> returns ["a","b","c"] |
如果要打开文件,需要使用完整路径:
1 2 3 4 | from os import path, listdir def getpaths(dirname): return [path.join(dirname, fname) for fname in listdir(dirname)] getpaths("test") #-> returns ["test/a","test/b","test/c"] |
您的问题的完整解决方案分为五行:
1 2 3 4 5 6 7 8 | import sys, os dir = sys.argv[1] files = [open(os.path.join(dir, f)) for f in os.listdir(dir)] first2lines = [' '.join(f.read().split(" ")[:2]) for f in files] print ' '.join(first2lines) |