对 Python 非常陌生,正在观看使用 VS Code 学习 Python 的在线视频教程。 以下代码用于生成文本文件:
#
# Read and write files using the built-in Python file methods
#
def main():
# Open a file for writing and create it if it doesn't exist
f = open("textfile.txt", "w+")
# Open the file for appending text to the end
# write some lines of data to the file
for i in range(10):
f.write("This is line " + str(i) + "\r\n")
# close the file when done
f.close()
# Open the file back up and read the contents
if __name__ == "__main__":
main()
当我运行它时,我得到:
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
而导师的输出是:
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
我曾尝试使用“\r\n”进行试验,当使用其中一个(如“\r”或“\n”)时,我得到了正确的响应,但两者结合使用会导致额外的行。
我在某处读到 Windows 和 Mac 在这方面存在差异,但我找不到关于这些字符是什么以及它们做什么的全部详细信息。
编辑:我用的是 Windows,导师用的是 Mac
请您参考如下方法:
在 Windows 上,当文件以文本模式(默认)打开时,写入\n 会转换为\r\n,因此写入\r\n 会得到\r\r\n。仅在文本模式下写入\n,这是可移植的,并且使用操作系统的正确行尾。
