[英]Python read from file - newline
I am writing a list (simple[]) to a file using writelines() and I need each item from the list to be on a new line in the file.我正在使用 writelines() 将列表 (simple[]) 写入文件,我需要列表中的每个项目都在文件中的新行上。 I am using the following code:
我正在使用以下代码:
file_path_simple = r'[path_redacted]\tx_list_simple.txt'
with open(file_path_simple, 'w') as fp:
for i in simple:
#ignores any blank lines
if i == '':
continue
else:
fp.writelines([i])
fp.writelines('\n')
fp.close()
The problem I am having is that when read from the file later it includes the \n, so instead of python reading:我遇到的问题是,稍后从文件中读取时它包含 \n,因此不是 python 读取:
blablabla
it reads:上面写着:
blablabla\n
How can I make it not read the \n?我怎样才能让它不读\n? Or do I need to use something like re.split() to remove the \n prior to reading?
或者我是否需要在阅读之前使用 re.split() 之类的东西来删除 \n ?
This seems like something really simple I am overlooking.这似乎是我忽略的非常简单的事情。
You can use rstrip
.您可以使用
rstrip
。
i = i.rstrip('\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.