Python从txt文件读取前两行

2024-03-28 18:51:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件topath用户inimport路径程序
3条回答

您似乎把内置的dir误认为是目录名;不,它不是。在

您应该将目录路径传递给os.chdir,而不是dir

os.chdir('/some/directory/path')

顺便说一句,您不需要将整个文件读入内存来获取您的两行代码,您只需在file对象上调用next

^{pr2}$

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

os.chdir(sys.argv[1])

如果文件只有一行,那么第二个next(f)将给出一个StopIteration异常,该异常应该被捕获,或者您可以将next(f, "")用于第二行,这将默认为空字符串,以防到达文件结尾。在

编辑:我走错了路。:(

好的,我现在编辑了代码,没有错误。现在的问题是,如果我用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

相关问题 更多 >