file.write(string)
其中,file 表示已经打开的文件对象;string 表示要写入文件的字符串(或字节串,仅适用写入二进制文件中)。例如,创建一个 a.txt 文件,该文件内容如下:注意,在使用 write() 向文件中写入数据,需保证使用 open() 函数是以 r+、w、w+、a 或 a+ 的模式打开文件,否则执行 write() 函数会抛出 io.UnsupportedOperation 错误。
阿俊的Python程序设计教程
http://web.suda.edu.cn/hejun/
- f = open("a.txt", 'w')
- f.write("写入一行新数据")
- f.close()
f = open("a.txt", 'w')
f.write("写入一行新数据")
f.close()
前面已经讲过,如果打开文件模式中包含 w(写入),那么向文件中写入内容时,会先清空原文件中的内容,然后再写入新的内容。因此运行上面程序,再次打开 a.txt 文件,只会看到新写入的内容:
写入一行新数据
- f = open("a.txt", 'a')
- f.write("\n写入一行新数据")
- f.close()
f = open("a.txt", 'a')
f.write("\n写入一行新数据")
f.close()
再次打开 a.txt,可以看到如下内容:
阿俊的Python程序设计教程
http://web.suda.edu.cn/hejun/
写入一行新数据
- f = open("a.txt", 'w')
- f.write("写入一行新数据")
- f.flush()
f = open("a.txt", 'w')
f.write("写入一行新数据")
f.flush()
打开 a.txt 文件,可以看到写入的新内容:
写入一行新数据
有读者可能会想到,通过设置 open() 函数的 buffering 参数可以关闭缓冲区,这样数据不就可以直接写入文件中了?对于以二进制格式打开的文件,可以不使用缓冲区,写入的数据会直接进入磁盘文件;但对于以文本格式打开的文件,必须使用缓冲区,否则 Python 解释器会 ValueError 错误。例如:
- f = open("a.txt", 'w',buffering = 0)
- f.write("写入一行新数据")
f = open("a.txt", 'w',buffering = 0)
f.write("写入一行新数据")
运行结果为:
Traceback (most recent call last):
File "C:\Users\mengma\Desktop\demo.py", line 1, in <module>
f = open("a.txt", 'w',buffering = 0)
ValueError: can't have unbuffered text I/O
with open("test.txt",mode='w') as fw: # 文本方式读取
fw.write("this is write test")
fw.write("\n")
with open("test.txt",mode='ab') as fw: # 二进制方式读取
s="中国人".encode()
fw.write(s)
例如,还是以 a.txt 文件为例,通过使用 writelines() 函数,可以轻松实现将 a.txt 文件中的数据复制到其它文件中,实现代码如下:注意,写入函数只有 write() 和 writelines() 函数,而没有名为 writeline 的函数。
执行此代码,在 a.txt 文件同级目录下会生成一个 b.txt 文件,且该文件中包含的数据和 a.txt 完全一样。
需要注意的是,使用 writelines() 函数向文件中写入多行数据时,不会自动给各行添加换行符。上面例子中,之所以 b.txt 文件中会逐行显示数据,是因为 readlines() 函数在读取各行数据时,读入了行尾的换行符。
with open("test.txt",mode='w') as fw: # 文本方式写入
seq=('1101', '张三', '20', '男') # 必须写入全是字符串
fw.writelines(seq)
with open("test.txt", "wb") as fw: # 二进制方式写入
seq = {'a':b"ffh4556 1\n", 'b':b"dfgr2\n",'c':b"1213"}
fw.writelines( seq.values() )
with open('multiplication.txt', 'w') as f:
for i in range(1, 10):
for j in range(1, i + 1):
result = str(j) + '*' + str(i) + '=' + str(i * j) + '\t'
print(result, end='')
f.write(result)
print()
f.write('\n')
with open('multiplication.txt', 'w') as f:
for i in range(1, 10):
for j in range(1, i + 1):
result = str(j) + '*' + str(i) + '=' + str(i * j) + '\t'
print(result, end='',file=f)
print(file=f)
import os
poet = ["静夜思\n", "作者:李白\n",
"床前明月光,\n", "疑是地上霜,\n",
"举头望明月,\n", "低头思故乡。"]
path = "E://Python教材例子"
if not os.path.exists(path):
print("文件夹不存在,先创建文件夹!")
os.makedirs(path)
print("文件夹创建成功!")
f = open("E://Python教材例子//poet.txt", 'w', encoding="utf8") # utf-8
f.writelines(poet)
f.close()
print("写入成功!")