我有一个 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"