简体   繁体   English

使用文件中的新行创建.TXT文件

[英]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: 然后执行以下操作:

  1. Put import os at the top. import os放在顶部。
  2. f.write("First line" + os.linesep)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 python 中重写一个 txt 文件,在有特定字符串的地方创建新行 - Rewriting a txt file in python, creating new lines where there is a certain string 如何使用txt文件中的行集? - How to work with the set of lines within the txt file? 将 txt 文件中的特定行复制到一个新的 txt 文件中 - Copy specific lines in txt file into one new txt file 用python在新行上将文本写入txt文件? - Writing text to txt file in python on new lines? 从 .txt 文件中删除重复项并创建新的 .txt 文件 - Removing duplicates from a .txt file and creating a new .txt file 使用Pandas使用.txt文件创建新的数据框 - Creating new dataframe with .txt file using Pandas 使用 another.txt 中的行创建 aa new.txt - Creating a a new .txt with lines from another .txt Python 如何在一个 file.txt 中写入 5 行,在一个新的 file1.txt 中写入另外 3 行,例如 +=1 - Python How to write 5 lines in one file.txt and the other 3 lines in a new file1.txt with +=1 for example Python,比较2个txt文件,找到第2个txt文件中唯一的行和output到一个新的txt文件 - Python, compare 2 txt files, find unique lines in the 2nd txt file and output to a new txt file 将 .txt 文件的特定行(包含大量行)写入新的 txt 文件 - Write specific lines of a .txt file ( containing large no of lines) to a new txt files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM