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

40次阅读
没有评论

共计 558 个字符,预计需要花费 2 分钟才能阅读完成。

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)

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计558字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)