首页 > 解决方案 > 是否可以将列表导出到 .txt 以便记事本可以读取换行符?

问题描述

出于可访问性的原因,我想知道在 python 中是否可以将列表导出到 .txt 以便记事本可以读取换行符?下面是一个在记事本++中正确读取但在记事本中不正确的示例代码。在记事本++中,列表的每个条目都在单独的行上,在记事本中,所有条目都在同一行上。

string =['str1 123','str2 234','str3 345']
outF = open("outp.txt", "w")
for item in string:
    outF.write("%s\n" % item)
outF.close()

标签: pythonwindows

解决方案


Windows 使用C arriage R eturn, Line Feed :来表示换行符\r\n,这是 Windows 记事本唯一识别的换行符:

In [7]: s = ['hello', 'world']

In [8]: with open('test.txt', 'w') as f:
   ...:     for item in s:
   ...:         f.write('%s\r\n' % item)

例子:

在此处输入图像描述

基于 Linux 的系统使用Line Feed来指示换行符,而旧的 Mac OS 过去只使用C arriage R eturn ,并且像 Notepad ++这样的编辑器可以配置为识别所有这些,而记事本则不能。


推荐阅读