前面已经介绍过了文件的打开和关闭以及访问模式,接下来介绍一下文件的读写以及一些常用的操作
文件的读写
写数据 write()
通过write方法向文件中写入数据,具体用法:文件对象.write(要写入文件的内容)
代码示例
f = open('test.txt','w',encoding='utf-8')
f.write('hello world')
f.write('\n')#换行
f.write('hello python')
f.close()
接下来打开test.txt文件会发现里面已经多了两行内容
hello world
hello python
这里我们采用的是w的访问模式,即当文件不存在时自动创建然后写入数据,当文件已存在时原有内容将被覆盖
写数据writelines()
writelines方法与write方法用法一样,不同的是在传入参数时可以把一个元组或一个列表作为参数,而列表或元组中的所有元素将被写入文件中
代码示例
f = open('test.txt','w',encoding='utf-8')
f.writelines(['hello world\n','hello python'])
f.close()
运行后打开test.txt同样会有两行内容
hello world
hello python