和前面python读取文件一样,写文件的操作也是相对简单的。首先,要写入文件必须的打开文件,在打开文件的时候,我们需要做一件事情:
with open(file_path, mode='w', encoding='utf-8') as file_obj:
大家注意到第二个参数了,这里是一个字符串,用来指定文件读写模式,
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)
在写入文件的时候,我们可以使用’w’、’a’、’r+’这几种模式。
首先我们看下’w‘模式:
file_path = 'data.txt'
with open(file_path, mode='w', encoding='utf-8') as file_obj:
file_obj.write('你好,Python!')
在这里我们打开文件,然后写入一行文字。在这里我们没有创建data.txt看下是否会生成这个文件:
运行我们的代码:
我们可以看到,文件正确的生成了,在python中当我们调用open函数并且将文件模式设置为’w’、’a’、’r+‘等具有写入权限的模式时,如果文件不存在,那么open函数会自动创建这个文件。
接下来我们看下,data.txt中是否和我们写入的内容一致:
大家也看到了,在我们输入的内容中包含有中文格式的字符,如果我们使用默认的编码格式,那么文件会产生乱码:
所以在处理中文相关的文件时,大家要留意一下当前编码格式是否能够正确处理中文。
在上面的基础上,我们向data.txt文件中重新输入一行文字:
file_path = 'data.txt'
with open(file_path, mode='w', encoding='utf-8') as file_obj:
file_obj.write('这是我第二次写:hello python!')
然后我们看下运行程序后,data.txt中的内容:
这里看到,前面我们写入的内容不见了,这里就得提一下如果我们使用’w’模式打开文件,在写入文件的时候,如果文件存在,那么python首先会清空该文件,然后写入我们的新内容。
如果我们要在文件后面追加我们的内容,这里我们就得使用’a’模式了:
with open(file_path, mode='a', encoding='utf-8') as file_obj:
运行结果:
写入的内容正确,但是大家可以发现,我们写入的内容write函数并没有给我加一个换行符,所以写入多行内容的时候,就像上边一样都是在一行,这里我们就得自己在我们写入的内容后面添加换行符了:
with open(file_path, mode='a', encoding='utf-8') as file_obj:
file_obj.write('hello python\n')
file_obj.write('这是我第二次写:hello python!\n')
运行结果: