TN8*_*888 1 python io file list
我想从文件中获取大量用户名 - 每行都是一个用户名.目前我使用此代码:
lista = []
z = open("usrnames.txt")
lista = z.readlines()
Run Code Online (Sandbox Code Playgroud)
但是,保存在列表中的结果是:
['username1\n', 'username2\n', 'username3\n']
Run Code Online (Sandbox Code Playgroud)
我不想要EOL ......我除了这个结果:
['username1', 'username2', 'username3']
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我阅读了这个函数的文档,并没有找到任何可以禁用EOL的参数...
你可以使用list comprehension strip:
lista = [line.strip() for line in z.readlines()]
Run Code Online (Sandbox Code Playgroud)
或简单地说,正如@Matthias所建议的那样:
lista = [line.strip() for line in z]
Run Code Online (Sandbox Code Playgroud)
或使用splitlines:
lista = z.read().splitlines()
Run Code Online (Sandbox Code Playgroud)