一.文件的打开与关闭
1.打开
如果当前目录有一个名为somefile.txt的文件,可以
f=open('somefile.txt)
若位于其他地方,可指定完整路径
2.关闭
1)可避免无意义锁定文件以防修改
2)避免用完系统可能指定的文件打开配额
3)写入过的文件一定要将其关闭,Python可能缓冲写入的数据,若程序由于某种原因崩溃,数据可能不会写入文件中
4)要确保文件得以关闭,可使用try/finally语句,如
#在这里打开文件
try:#将数据写入到文件中
finally:
file.close()
更有专门为此设计的with语句,如
with open("somefile.txt") as somefile:
do_something(somefile)
with语句能打开文件并将其赋给一个变量,在语句体中,将数据写入文件,在到达语句末尾,将自动关闭文件
二.文件模式
值
描述
'r'
读取模式(默认)
'w'
写入模式
'x'
独占写入模式
'a'
附加模式
'b'
二进制模式(与其他模式结合使用)
't'
文本模式(默认值,结合使用)
'+'
读写模式,结合使用
1.写入模式:能写入文件,并在文件不存在时创建。在此模式下打开文件,文件内容会被删除(截断),并从文件开头写入
2.独占模式:在文件存在时引发FileExistsError异常
3.附加模式:在已有文件末尾继续写入
4.'+'与任意模式结合,表示即可读入,又可写入。'w+'会截断文件,'r+'不会
三.基本方法
1.写入
f = open('somefile.txt', 'w')
f.write('Hello,')
f.write('World!')
f.close()
2.读取
read()
f = open('somefile.txt', 'r')print(f.read(4))#Hell 光标移到l后print(f.read())#o, World! 从l后输出内容
f.close()
readline()
#somefile.txt内容
'''
Welcome to this file
There is nothing here except
This stupid haiku
'''
f = open(r'C:\text\somefile.txt')for i in range(3):print(str(i) + ':' + f.readline(), end='')
'''
0: Welcome to this file
1: There is nothing here except
2: This stupid haiku
'''
readlines()
importpprint
pprint.pprint(open(r'C:\text\somefile.txt').readlines())
"""
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']
"""