<p>我正在尝试创建一个程序,它读取用户给定的路径,然后读取位于该特定路径的前两行txt文件。在</p>
<p>问题是我得到了这个错误:</p>
<p>TypeError:强制转换为Unicode:需要字符串或缓冲区,找到了内置函数\u或\u方法</p>
<p>我不明白为什么?在</p>
<pre><code>#!/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
</code></pre>