Python保存文本文件的方法有以下几种:
- 使用open()函数和write()方法将内容写入文件:
file = open("filename.txt", "w") file.write("Hello, World!") file.close()
- 使用with语句自动关闭文件:
with open("filename.txt", "w") as file: file.write("Hello, World!")
- 使用file.write()方法将多行文本写入文件:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("filename.txt", "w") as file: file.writelines(lines)
- 使用print()函数将内容写入文件:
with open("filename.txt", "w") as file: print("Hello, World!", file=file)
- 使用numpy库的savetxt()函数保存数组数据为文本文件:
import numpy as np data = https://www.yisu.com/ask/np.array([[1, 2, 3], [4, 5, 6]])"filename.txt", data)
以上是几种常用的保存文本文件的方法,可以根据具体需求选择适合的方法。