Python write写文件

Python write写文件教程

Python 中,写文件内容之前首先需要使用 open 函数以写入模式打开文件。 Python 写文件有两种方法,分别为:使用 write 函数 写文件与使用 writelines 写文件。

write写文件详解

语法

n = file.write(string)

参数

参数 描述
n 写入成功的字节数。
file 文件对象。
string 要写入的文件内容。

返回值

返回写入成功的字节数。

说明

file 表示已经打开的文件对象,string 表示要写入文件的 字符串。 函数的 返回值 n 是一个 int类型 的整数,表示写入了多少个字节。

在使用 write() 向文件中写入数据,需保证使用 open() 函数是以 r+、w、w+、a 或 a+ 的模式打开文件,否则执行 write() 函数会抛出 io.UnsupportedOperation 错误。

案例

使用write函数写文件

使用 write 函数向已打开的文件写入内容

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt", "w") n = file.write("Hello HaiCoder") print("Write =", n) file.close()

程序运行后,控制台输出如下:

34_Python write函数写文件.png

我们使用 open 函数以写模式打开文件,接着使用 open 函数返回的文件对象调用 write 函数写文件,并返回成功写入文件的字节数 n。文件写入成功后,需要使用 close 函数关闭打开的文件,不然会造成资源泄露。

使用 “w” 模块打开文件,如果文件存在,则会清空文件内容,进行写入,如果文件不存在,则会首先创建文件,然后再进行写入。现在,文件已经写入成功,我们再次使用如下程序,读取文件:

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt") s = file.read() print("File Content =", s) file.close()

程序运行后,控制台输出如下:

35_Python write函数写文件.png

我们使用 read 读取刚打开的文件,此时读取出了我们之前写入的文件内容。

使用write函数追加写文件

使用 write 函数向已打开的文件中追加写入内容

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt", "a") n = file.write("Hello HaiCoder") print("Write =", n) file.close()

程序运行后,控制台输出如下:

36_Python write函数写文件.png

我们使用 open 函数以追加模式打开文件,接着,我们多次运行该程序。现在,文件已经写入成功,我们再次使用如下程序,读取文件:

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt") s = file.read() print("File Content =", s) file.close()

程序运行后,控制台输出如下:

37_Python write函数写文件.png

我们使用 read 读取刚写入的文件,此时我们发现文件内容已经被写入了多次。

使用write函数写入一行文件

使用 write 函数向已打开的文件中追加一行文件内容

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt", "a") n = file.write("Hello HaiCoder\n") print("Write =", n) file.close()

程序运行后,控制台输出如下:

38_Python write函数写文件.png

我们在使用 write 写入文件时,在每行的后面使用了 “\n” 表示每写一次进行一次换行,我们再次使用如下程序,读取文件:

print("嗨客网(www.haicoder.net)") file = open("C:/haicoder.txt") s = file.read() print("File Content =", s) file.close()

程序运行后,控制台输出如下:

39_Python write函数写文件.png

我们使用 read 读取刚写入的文件,此时我们发现文件内容的内容是换行的。

Python write写文件总结

Python write 写文件文件语法语法:

n = file.write(string)

file 表示已经打开的文件对象,string 表示要写入文件的字符串。 函数的返回值 n 是一个 int 类型的整数,表示写入了多少个字节。

在使用 write() 向文件中写入数据,需保证使用 open() 函数是以 r+、w、w+、a 或 a+ 的模式打开文件,否则执行 write() 函数会抛出 io.UnsupportedOperation 错误。