在Python中创建文件。初学者。如何格式化已创建文件中的文本
这里的第一篇文章……我正在学习Python,并且能够学习如何从Python创建.txt文件。然而,在我接下来的教程中,一旦我运行代码,我应该会在.txt文件中看到这4行代码 你好,世界在Python中创建文件。初学者。如何格式化已创建文件中的文本,python,Python,这里的第一篇文章……我正在学习Python,并且能够学习如何从Python创建.txt文件。然而,在我接下来的教程中,一旦我运行代码,我应该会在.txt文件中看到这4行代码 你好,世界 这是我们的新文本文件 这是另一行。 为什么?因为我们可以 但是,我创建文件后看到的是: 你好,这是我们的新文本文件,这是另一行。为什么?因为我们可以 基本上,我看到的不是4条不同的线,而是所有东西都在同一条线上。我的问题是,我如何确保我得到了4行,而不是所有的东西在一起。谢谢,这是我的代码: file = ope
这是我们的新文本文件
这是另一行。
为什么?因为我们可以 但是,我创建文件后看到的是: 你好,这是我们的新文本文件,这是另一行。为什么?因为我们可以 基本上,我看到的不是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()
欢迎来到Python
您需要告诉python您希望通过在每个write语句中添加“\n”来结束该行:
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
您需要告诉python您希望通过在每个write语句中添加“\n”来结束该行:
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()
在文本之间使用“\n”,从此处开始新行。如以下示例所示:
代码:
f = open("Hello.txt","w")
f.write("This is first line.\nThis is second line.")
f = open("Hello.txt","r")
print(f.read())
输出:
This is first line.
This is second line.
在文本之间使用“\n”,从此处开始新行。如以下示例所示:
代码:
f = open("Hello.txt","w")
f.write("This is first line.\nThis is second line.")
f = open("Hello.txt","r")
print(f.read())
输出:
This is first line.
This is second line.
您可以在Python 3中使用print()
:
f = open('Hello.txt', 'w')
print('Hello World', file=f)
print('This is our new text file', file=f)
以下内容适用于Python2和Python3
f = open('Hello.txt', 'w')
f.write("Hello World\n")
f.write("This is our new text file\n")
f.close()
\n
将由Python自动转换为os.linesep
。您可以在Python 3中使用print()
:
f = open('Hello.txt', 'w')
print('Hello World', file=f)
print('This is our new text file', file=f)
以下内容适用于Python2和Python3
f = open('Hello.txt', 'w')
f.write("Hello World\n")
f.write("This is our new text file\n")
f.close()
\n
将由Python自动转换为os.linesep
。“Hello World\n”“Hello World\n”非常感谢您非常感谢您说我的声誉不允许我投票/它说我的名声不允许我投票/