文件操作三步走:打开、读写、关闭。
open(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file参数指定了被打开的文件名称。
mode参数指定了打开文件后的处理方式。
encoding参数指定对文本进行编码和解码的方式,只适用于文本模式,可以使用Python支持的任何格式,如GBK、utf8、CP936等等。
文件打开模式


例:向文本文件中写入内容,然后再读出
s = ‘Hello world\n文本文件的读取方法、文本文件的写入方法\n‘
with open(‘sample.txt‘,‘w‘) as fp: #默认使用cp936编码
fp.write(s*5)
#生成的文件放在.py文件所在文件夹
with open(‘sample.txt‘) as fp:
print(fp.read())
E:\pytho_pycharm\venv\Scripts\python.exe E:/pytho_pycharm/prac.py
Hello world
文本文件的读取方法、文本文件的写入方法
Hello world
文本文件的读取方法、文本文件的写入方法
Hello world
文本文件的读取方法、文本文件的写入方法
Hello world
文本文件的读取方法、文本文件的写入方法
Hello world
文本文件的读取方法、文本文件的写入方法
Process finished with exit code 0
例:将一个CP936编码格式的文本文件中的内容全部复制到另一个使用UTF8编码的文本文件中。
#将一个CP936编码格式的文本文件中的内容全部复制到另一个使用UTF-8编码的文本文件中
def filecopy(srcc,dstt,srccEncoding,dsttEncoding):
with open(srcc,‘r‘,encoding=srccEncoding) as srcfp:
with open(dstt,‘w‘,encoding=dsttEncoding) as dstfp:
dstfp.write(srcfp.read())
filecopy(‘sample.txt‘,‘sample_new.txt‘,‘cp936‘,‘utf8‘)
#读取这两个文件
with open(‘sample.txt‘) as fp: #默认为CP936编码
print(fp.read())
print()
with open(‘sample_new.txt‘,encoding=‘utf-8‘) as fp: #如果是其他编码需要有(encoding = )
print(fp.read())
例:遍历并输出文本文件的所有行内容
with open(‘sample.txt‘) as fp:
for line in fp:
print(line,end=‘‘)
原文:https://www.cnblogs.com/jiaxinwei/p/11624265.html