【发布时间】:2017-10-02 13:23:29
【问题描述】:
我正在尝试创建一个程序来读取用户给出的路径,然后读取该特定路径中存在的前两行 txt 文件。
问题是我收到了这个错误:
"TypeError: coercing to Unicode: need string or buffer, builtin_function_or_metho d found"
我不明白为什么?
#!/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
【问题讨论】:
-
对于初学者,您正在打印第 2 行和第 3 行。请提供完整的错误消息,包括回溯。
-
os.chdir(dir)你认为dir在这一行中代表什么? -
好像
f.close,不是吗?