将文件读取到Python中的字符串列表

Han*_*nah 1 python file list

当您在Python中使用fileName.readlines()函数时,列表中是否包含文件末尾的符号?

例如,如果文件被读入字符串列表而最后一行是"结束",列表中是否会有另一个地方带有表示文件末尾的符号?

谢谢.

Joh*_*ooy 5

不,该列表包含文件中每行的一个元素.

您可以对a中的每一行执行某些操作,如下所示:

lines = infile.readlines()
for line in lines:
    # Do something with this line
    process(line)
Run Code Online (Sandbox Code Playgroud)

Python有一种更短的方法来实现这一点,避免一次将整个文件读入内存

for line in infile:
    # Do something with this line
    process(line)
Run Code Online (Sandbox Code Playgroud)

如果你只想要文件的最后一行

lines = infile.readlines()
last_line = lines[-1]
Run Code Online (Sandbox Code Playgroud)

为什么你认为最后需要一个特殊的符号?