我正在尝试创建一个程序,它读取用户给定的路径,然后读取位于该特定路径的前两行txt文件。在
问题是我得到了这个错误:
TypeError:强制转换为Unicode:需要字符串或缓冲区,找到了内置函数\u或\u方法
我不明白为什么?在
#!/usr/bin/python
import glob, os
import sys
#Check to see that path was privided
if len(sys.argv) < 2:
print "Please provide a path"
#Find files in path given
os.chdir(dir)
#Chose the ones with txt extension
for file in glob.glob("*.txt"):
try:
#Read and output first two lines of txt file
f = open(file)
lines = f.readlines()
print lines[1]
print lines[2]
fh.close()
#Catch exception errors
except IOError:
print "Failed to read " + file
您似乎把内置的
dir
误认为是目录名;不,它不是。在您应该将目录路径传递给
os.chdir
,而不是dir
:顺便说一句,您不需要将整个文件读入内存来获取您的两行代码,您只需在file对象上调用
^{pr2}$next
:另外,如果输入中没有路径,则应在打印错误消息后退出,否则将获得
如果文件只有一行,那么第二个
next(f)
将给出一个StopIteration异常,该异常应该被捕获,或者您可以将next(f, "")
用于第二行,这将默认为空字符串,以防到达文件结尾。在编辑:我走错了路。:(
好的,我现在编辑了代码,没有错误。现在的问题是,如果我用
python readfiles.py /home/
运行它,什么都不会发生?在相关问题 更多 >
编程相关推荐