目录:
1.文件打开方式
2.文件内容读取
3.文件内容写入
4.文件扩展用法
1.文件打开方式
open函数,返回值是个文件对象
file_object = open(file_url,access_mode = ‘r’)
file_url:
文件路径:相对路径和绝对路径
access_mode:
读
写
读+写
#1.文件打开
fileDir = 'D:/Pytest1.txt'
fileDir1 = 'D:\\Pytest2.txt' #最好用两个反斜杠,以防有文件名以n开头,和斜杠在一起会被转义。
fileDir2 = r'D:\pytest3.txt' #r 取消转义,只能在python中用
2.文件内容读取
fo.read() #读取和光标类似
后面演示读取的文本中包含的内容
文件关闭:
fo.close() #关闭内存对象
fo.tell() 返回当前光标所在位置
文件指针移动
fo.seek()
fileDir = 'E:/test/test1.txt'
fo = open(fileDir)
print(fo.tell())
print(fo.read(2))
print('读操作后------>',fo.tell())
fo.seek(1,0) #(移动到的位置,模式) 0模式,从文件指针最开始的地方0开始。0模式一般用于文本文档
print('seek操作后------>',fo.tell())
# fo.seek(3,0)
# print('seek操作后------>',fo.tell())
print('****************************')
#1模式和2模式一般用于二进制文件,比如音频,抓包文件,视频,图片等。此时,open函数后要选择二进制模式,如下例所示
#1模式从光标当前位置移动,2模式从尾部移动
fileDir = 'E:/test/test1.txt'
fo = open(fileDir,'rb')
print(fo.tell())
print(fo.read(2))
print('读操作后------>',fo.tell())
fo.seek(1,1)
print('seek操作后------>',fo.tell())
读取一行
fo.readline()
读取多行-----返回list列表
fo.readlines()
读取所有行------去换行符\n-----返回是list
使用方法.splitlines()
注意,只能和read()一起用,不能喝readlines()用,会报错
fileDir = 'E:/test/test1.txt'
fo = open(fileDir)
print(fo.readline())
print(fo.read().splitlines())
fo.close()
3.文件内容写入
如果不存在,会新建,如果存在,会清空所有内容,重新写入
fileDir = 'E:/test/test1.txt'
fo = open(fileDir,'w')
运行后,test1.txt里已经没有内容了
如下这种情况,在pycharme中无法观察,应该在控制台下执行,可以观察到。
fileDir = 'E:/test/test1.txt'
fo = open(fileDir,'w')
fo.write('abcdefg') #本质是不写磁盘,写在缓存里。
如果想执行完后,写入磁盘,应该刷新到磁盘中,如下操作。
fileDir = 'E:/test/test1.txt'
fo = open(fileDir,'w')
fo.write('abcdefg') #本质是不写磁盘,写在缓存里。
fo.flush() #通过这个命令吧缓存里的内容刷新都磁盘中
如果不想每次输入后都清空之前的内容,可以用追加的方式输入文本。如下所示。
文本内容如下图