使用 "with" 命令打开文件名列表创建的不是字符串列表而是字符列表

open list of file names with "with" command creates not list of strings but a list of characters

我有一个名为 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的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

作为列表理解:

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

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