【问题标题】:Python - Reading first two lines from txt filesPython - 从 txt 文件中读取前两行
【发布时间】: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,不是吗?

标签: python readline


【解决方案1】:

您似乎将内置的dir 误认为是目录名称;不,不是。

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

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

顺便说一句,你不需要将整个文件读入内存来获取你的两行,你可以简单地在文件对象上调用next

with open(file) as f:
    line1, line2 = next(f), next(f)

【讨论】:

  • 好的,谢谢。但是目录路径是作为参数发送的,它不是硬编码的。我在 linux 的命令行上运行 python。
  • 从命令行作为参数传递? os.chdir(sys.argv[1])
【解决方案2】:

另外,如果输入中没有路径,打印错误信息后应该退出,否则会得到IndexError for

os.chdir(sys.argv[1])

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

【讨论】:

    【解决方案3】:

    编辑:我输入了错误的路径。 :(

    好的,所以我现在已经编辑了代码,我没有收到任何错误。现在的问题是,如果我用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
    

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 2021-12-28
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多