没有 \n 有什么方便的方法来读取行吗?

Is there any convenient way to readline without the \n?

我有一个名为read_proxy的函数,我想阅读文本的每一行:

def read_proxy():
    f = open('./proxy.txt', 'r')
    proxies = f.readlines()
    f.close()
    return proxies

if __name__ == '__main__':

    proxies = read_proxy()
    print(proxies)  # ['a\n', 'sad\n', 'asdasd\n', 'asdas\n', '1223\n', '43\n', '4576\n', '789\n', '90900-\n']
    

您看到列表项,每个列表项的末尾都有一个 \nread_proxy()怎么写,让我实现得到每行字符串不带\n?在我的选择中,我只能对每个项目进行 forloop,然后将 \n 去掉。

def read_proxy_without_newlines():
    f = open('./proxy.txt', 'r')
    proxies = f.readlines()
    f.close()
    return [p.rstrip('\n') for p in proxies]

而不是使用 .readlines(),它将每一行分别读取到列表中并在末尾保留 \n,您可以尝试使用 .read() 来获取整个文件一次,然后使用 str.split() 将其变成行列表,但这次 删除 换行符:

def read_proxy():
    f = open('./proxy.txt', 'r')
    proxies = f.read().split('\n')
    f.close()
    return proxies

我不确定为什么 Python 决定这样做,而是遍历文件 returns 它的行。所以你也可以这样写:

with open('./proxy.txt', 'r') as file:
    return [line.rstrip('\n') for line in file]

对于非常大的文件,这可能比将整个文件读入内存然后解析它更有效。内存中不需要文件的两份副本(一份有换行符,一份没有)。