Python - 从txt文件中读取前两行

时间:2017-05-04 11:27:30

标签: python readline

我正在尝试创建一个程序来读取用户给出的路径,然后读取存在于该特定路径的前两行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

3 个答案:

答案 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)

另外,如果输入中没有路径,则应在打印错误消息后退出,否则会出现

的IndexError
os.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
相关问题