![](/img/trans.png)
[英]Rewriting a txt file in python, creating new lines where there is a certain string
[英]Creating a .TXT file with new lines within the file
写入txt文件中的文件时出现问题,它没有将第二条消息放置到下一行。 (当它打印到屏幕上时,它可以按照我的预期工作,但不在文件本身中)
注意:我的python版本是2.7.3
import os.path
home = os.path.expanduser("~")
check1 = os.path.exists(home + '/test.txt')
if check1 == False:
f = open(home + '/test.txt', 'a')
f.write("First line\n")
f.write("Second line")
f.close()
elif check1 == True:
with open(home + '/test.txt') as f:
for line in f:
print line
f.close()
这是我的代码的基础。
谢谢斯图尔特
您使用Unix样式行结尾,然后使用Windows特定的文本查看器查看它。 记事本无法将\\n
识别为换行符; 它需要Windows样式行的结尾: \\r\\n
。
阅读有关行尾以及不同操作系统具有不同默认值的信息。 提高您的意识和对此问题的了解。 然后执行以下操作:
import os
放在顶部。 f.write("First line" + os.linesep)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.