用Python创建文件。初学者。如何在创建的fi中格式化文本

2024-10-06 11:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

第一篇文章…我正在学习Python,我能够学习如何从Python创建一个.txt文件。但是,在我接下来的教程中,一旦我运行代码,我应该会在.txt文件中看到这4行代码

你好世界
这是我们的新文本文件
这是另一条线。
为什么?因为我们可以。在

但是,创建文件后,我看到的是:

你好世界这是我们的新文本文件,这是另一个行。为什么?因为我们可以。在

基本上,我看到的不是4条不同的线,而是一条线。我的问题是,我怎样才能确保我得到了4条线,而不是所有的东西都在一起。谢谢,这是我的密码:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w") 

file.write("Hello World") 
file.write("This is our new text file") 
file.write("and this is another line.") 
file.write("Why? Because we can.") 

file.close() 

Tags: 文件代码txt密码is文章世界教程
3条回答

欢迎来到Python!在

您需要通过在每个write语句中添加“\n”来告诉python要结束该行:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w") 

file.write("Hello World\n") 
file.write("This is our new text file\n") 
file.write("and this is another line.\n") 
file.write("Why? Because we can.\n") 

file.close() 

您可以在Python 3中使用print()

f = open('Hello.txt', 'w')
print('Hello World', file=f)
print('This is our new text file', file=f)

以下内容适用于python2和python3。在

^{pr2}$

\n将由Python自动转换为os.linesep。在

从“\n”之间的新文本开始。如下例所示:

代码:

f = open("Hello.txt","w")
f.write("This is first line.\nThis is second line.")

f = open("Hello.txt","r")
print(f.read())

输出:

^{pr2}$

相关问题 更多 >