读取不带\n python 的.txt 文件 3.6

Read .txt files without \n python 3.6

我正在阅读来自 python 的 .txt 文件。这被用作我的程序的配置文件。

唯一的问题是,当我使用 .readlines() 函数时,它 returns 一个带有“\n”的文本列表,只要有一个新行。有没有办法在最后没有这些的情况下读取文件?

这将使根据配置文件调整变量变得更加容易。

文本文件:

800
500
212,122,122

这是代码:

config = open("config.txt", "r")
config = config.readlines()
print(config)

输出:

['800\n', '500\n', '212,122,122']

readlines 包括您不需要的行分隔符。

就这样:

config = [x.rstrip("\n") for x in config.readlines()]

或者简单地使用 splitlines() 相当于 split("\n")

config = config.read().splitlines()

最好的内存方式是使用文件迭代器来避免一次读取所有文件(迭代器也 returns 换行符):

config = [x.rstrip("\n") for x in config]

附带说明一下,覆盖文件句柄变量名不是很明智。最好使用 2 个不同的变量名称作为句柄和行列表以及上下文管理器 (with open("xxx") as config:) 而不是 config = open(...)

你可以试试这个

config = open("config.txt", "r")
config = config.read().splitlines()
print(config)

结果 ['800', '500', '212,122,122']