我正在尝试创建一个程序来读取用户给出的路径,然后读取存在于该特定路径的前两行txt文件。
问题是我收到了这个错误:
“TypeError:强制转换为Unicode:需要字符串或缓冲区,找到builtin_function_or_metho”
我不明白为什么?
#!/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
答案 0 :(得分:1)
您似乎误将内置dir
误认为是目录名称;不,不是。
您应该将目录路径传递给os.chdir
而不是dir
:
os.chdir('/some/directory/path')
顺便说一下,您不需要将整个文件读入内存以获取两行,您只需在文件对象上调用next
:
with open(file) as f:
line1, line2 = next(f), next(f)
答案 1 :(得分:0)
另外,如果输入中没有路径,则应在打印错误消息后退出,否则会出现
的IndexErroros.chdir(sys.argv[1])
如果文件只有一行,则第二个next(f)
会给出一个StopIteration异常,应该被捕获,或者你可以使用next(f, "")
作为第二行,这将默认为如果到达文件末尾,则为空字符串。
答案 2 :(得分:0)
好的,所以我现在编辑了代码,没有错误。问题现在是,如果我用python readfiles.py /home/
运行它没有任何反应?
#!/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"
sys.exit()
#Find files in path given
os.chdir(sys.argv[1])
#Chose the ones with txt extension
for file in glob.glob("*.txt"):
try:
#Read and output first two lines of txt file
with open(file) as f:
line1, line2 = next(f), next(f, "")
print line1 + " " + line2
#Catch exception errors
except IOError:
print "Failed to read " + file