open函数,该函数用于对文件进行读取和写入等处理,
一、打开文件
文件句柄 = open(‘文件路径’, ‘模式’)
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,便可以通过此文件句柄对该文件进行增删改查等操作。
打开文件的模式有:
r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
“+” 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
x+ ,写读【可读,可写】
a+, 写读【可读,可写】
"b"表示以字节的方式操作
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
例:
以下是test.txt文件的内容:
hello worldalexhgia
greihi
hmoerjgo
mgrljaob
hello worldalexhello worldalexhello worldalex
1、r模式
f=open('test','r',encoding='utf-8')#对象
data=f.read(5)#,参数是几就是几个字符,5是5个字符
print(data,type(data)) #hello <class 'str'>
f.close()
2、w模式
’w’是对文件清空之后,在创建对象时已经清空了,如果没有文件,则会创建文件在写
f=open('test','w',encoding='utf-8')#对象
f.write('python hello')
f.write('\nxiaxiao')
f.close()
运行结果如下:原来的test文件的内容被清空之后,又分别把python hello和xiaoxiao写进文件里面。(注意的是文件读写可以识别里面的转义字符等,比如\n换行符,自由open函数对文件读写后必须进行文件操作关闭)
3 、r+模式
f=open('test','r+',encoding='utf-8')#对象
print(f.readline().strip())
print(f.readlines())#列表
f.close()
运行结果:
python hello!!!
['xiaxiao']
4、for循环遍历文件句柄,并对文件进行插入内容。
f=open('test','r+',encoding='utf-8')#对象
num=0
for i in f.readlines():
num+=1
if num==6:
i=''.join((i.strip(),'kjgika'))#如果没有strip(),会识别文档的换行符,print也会换行。
print(i.strip())
f.close()#如果不关闭,则会出现数据不安全。
运行结果:
或者:
f=open('test','r+',encoding='utf-8')
i=f.readlines()#一行一行的读文件,以列表的形式返回,并把文件的所有符号都读出来比如:\n
print (i)
print(''.join((i[5].strip(),'haug8r8g')))
f.close()
运行结果:
['python hello!!!\n', 'xiaxiao\n', 'ngakgka\n', '尼康人口昂开始\n', '那个谁坑看房卡人那可能风格可谓\n', 'ngkangla\n', 'gnealgmlr\n', '南瓜能够拉搞忘记该']
ngkanglahaug8r8g
或者最优方式
f=open('test','r+',encoding='utf-8')
num=0
for i in f:#f这是for内部将f对象做成迭代器,用一行取一行,打开文件最优方式
num+=1
if num==6:
i=''.join((i.strip(),'kjgika'))
print(i.strip())
运行结果:
5、两个文件读写同时进行
f_read = open('test','r',encoding='utf-8')
f_write = open ('test1','w',encoding='utf-8')
num=0
for line in f_read:
num+=1
if num==5:
line = ''.join([line.strip(),'\nakglaalex\n'])#‘’.是以空格为分隔符。
f_write.write(line)
运行结果:
6、with,推荐用这种方式。为了避免打开文件忘记关闭,可以通过管理上下文。当with代码块执行完毕时,内部会自动关闭并释放文件资源
#with同时管理多个文件对象
num=0
with open ('test','r',encoding='utf-8') as f_read,open('tests','w',encoding='utf-8') as f_write:
for line in f_read:
num+=1
if num==5:
line=''.join([line.strip(),'\n我爱python!!!\n'])
f_write.write(line)
运行之后,tests文件如下: