使用 .readlines() 时摆脱 \n [英] Getting rid of \n when using .readlines()

查看:47
本文介绍了使用 .readlines() 时摆脱 \n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含值的 .txt 文件.

I have a .txt file with values in it.

值如下列出:

Value1
Value2
Value3
Value4

我的目标是将值放入列表中.当我这样做时,列表如下所示:

My goal is to put the values in a list. When I do so, the list looks like this:

['Value1\n', 'Value2\n', ...]

不需要\n.

这是我的代码:

t = open('filename.txt', 'r+w')
contents = t.readline()

alist = []

for i in contents:
    alist.append(i)

推荐答案

这应该可以满足您的需求(列表中的文件内容,按行,不带 \n)

This should do what you want (file contents in a list, by line, without \n)

with open(filename) as f:
    mylist = f.read().splitlines() 

这篇关于使用 .readlines() 时摆脱 \n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆