[英]Creating a .TXT file with new lines within the file
I am having issues when writing the file that within the txt file it does not place the second message to the next line. 写入txt文件中的文件时出现问题,它没有将第二条消息放置到下一行。 (When it prints to the screen it work as I intend it to work, but not in the file itself)
(当它打印到屏幕上时,它可以按照我的预期工作,但不在文件本身中)
Note: My python version is 2.7.3 注意:我的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()
this is the basis for my code. 这是我的代码的基础。
Thank you, Stuart 谢谢斯图尔特
You used a Unix style line ending and then used a Windows specific text viewer to look at it. 您使用Unix样式行结尾,然后使用Windows特定的文本查看器查看它。 Notepad doesn't recognize a
\\n
as a newline character; 记事本无法将
\\n
识别为换行符; it requires Windows style line endings: \\r\\n
. 它需要Windows样式行的结尾:
\\r\\n
。
Go read up about line endings and how different OSes have different defaults. 阅读有关行尾以及不同操作系统具有不同默认值的信息。 Increase your awareness and your knowledge of this issue.
提高您的意识和对此问题的了解。 Then do this:
然后执行以下操作:
import os
at the top. import os
放在顶部。 f.write("First line" + os.linesep)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.