温馨提示×

python保存文本文件的方法有哪些

小亿
145
2023-09-13 14:50:33
栏目: 编程语言

Python保存文本文件的方法有以下几种:

  1. 使用open()函数和write()方法将内容写入文件:
file = open("filename.txt", "w")
file.write("Hello, World!")
file.close()
  1. 使用with语句自动关闭文件:
with open("filename.txt", "w") as file:
file.write("Hello, World!")
  1. 使用file.write()方法将多行文本写入文件:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("filename.txt", "w") as file:
file.writelines(lines)
  1. 使用print()函数将内容写入文件:
with open("filename.txt", "w") as file:
print("Hello, World!", file=file)
  1. 使用numpy库的savetxt()函数保存数组数据为文本文件:
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("filename.txt", data)

以上是几种常用的保存文本文件的方法,可以根据具体需求选择适合的方法。

0