f = open("test3.txt", mode='x') # 打开文件test3.txt,f相当于文件句柄
# 如果要写中文,需如下语句
# f = open("test3.txt",mode='x', encoding='utf8')
f.write("line 1\n")
f.writelines(["line 2\n", "line 3"])
f.close() # 关闭文件
在工程目录下,会产生一个test3.txt文件,内容如下
line 1
line 2
line 3
# open()函数的mode参数如下
'r' open for reading (default) --读
'w' open for writing, truncating the file first --清空并写
'x' create a new file and open it for writing --创建打开并写
'a' open for writing, appending to the end of the file if it exists --打开并追加写
'b' binary mode --二进制写
't' text mode (default) -文本模式写
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated) --已淘汰