【问题标题】:open list of file names with "with" command creates not list of strings but a list of characters使用“with”命令打开文件名列表不是创建字符串列表,而是创建字符列表
【发布时间】:2015-07-09 08:06:56
【问题描述】:

我有一个名为files.txt 的文件,其中包含文件名。像这样:

L150216_1.txt_out

L150216_2.txt_out

L150216_3.txt_out

我正在像这样打开files.txt

with open("files.txt") as f:
    file_List = f.read()
    pass #Do some calculations with the file_List

然而,事实证明,file_List 看起来不像文件名列表,而是字符列表。 IE。而不是 L150216_1.txt_out 它将是 L、1、5、0 等等。

如何使用"with" 命令打开文件以读取行而不是字符?

【问题讨论】:

    标签: python list with-statement


    【解决方案1】:

    Python的with命令没有错,意外的行为是由于read(),如果你真的想获取正在读取的文件的各个行中的字符串列表,那么你必须使用file.readlines() .

    with open("files.txt") as f:
        file_List = f.readlines()
        #Now file_List is a list as
        #["file1.txt", "file2.txt", "file3.txt"]
        pass #Do some calculations with the file_List
    

    【讨论】:

      【解决方案2】:

      作为列表理解:

      lines = [line.strip() for line in open('files.txt')]
      

      但请记住,每行后面的空格将在列表中显示为''

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 2011-04-20
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 2014-02-10
        • 2016-02-13
        相关资源
        最近更新 更多