要在Python中新建文件并写入数据,可以使用以下方法:
open()函数创建文件对象,并指定打开模式为写入模式("w")。例如:file = open("filename.txt", "w")write()方法将数据写入文件。例如:file.write("Hello, World!")close()方法关闭文件。例如:file.close()完整的代码示例如下:
file = open("filename.txt", "w")
file.write("Hello, World!")
file.close()
另外,还可以使用with语句来自动管理文件的打开和关闭,这样可以更安全和简洁:
with open("filename.txt", "w") as file:
file.write("Hello, World!")
使用with语句后,不需要再调用close()方法来关闭文件,当with语句结束时,文件会自动关闭。