python文件操作

本文介绍python中的文件操作知识。在学习文件操作前,了解路径、进制和编码对学习有很大帮助。

文件操作的一般步骤:打开文件;读写文件;关闭文件。

打开文件使用python的内置函数open()

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

  Open file and return a stream.  Raise OSError upon failure. 

   文件打开模式

r       不存在报错,存在只读
w      不存在则创建写,存在则清空文件写
x       不存在则创建写,存在则会报错
a       不存在则创建写,存在则尾部写

b       二进制字节--binary
t        二进制文本字符串--text

+   可读可写

#注意光标位置,写入会覆盖,读取自光标开始

# r+ 模式相当于两个光标。一个读光标在开头,一个写光标在结尾。

# w+ 模式可同时读写

# a+ 模式读写都在尾部

     'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)


一、以字节(byte)的方式读写文件。

#字符串压缩为字节
date = '字节byte'
transform = date.encode('utf-8')
# print(transform)#字节类型:b'\xe5\xad\x97\xe8\x8a\x82byte'

#文件操作————写入byte类型
file_object = open('D:/lx/study_python/iris/log.txt',mode = 'wb')   #打开文件
file_object.write(transform)     #写入内容
file_object.close()     #关闭文件


#文件操作————读byte类型
file_object = open('D:/lx/study_python/iris/log.txt',mode = 'rb')   #打开文件
date = file_object.read()       #读取文件
file_object.close()     #关闭文件
# print(date)##字节类型:b'\xe5\xad\x97\xe8\x8a\x82byte'

#字节解压为字符串
old = date.decode('utf-8')
# print(old)#字符串类型:字节byte

二、以字符串(str)的方式读写文件

#读str文件,先判断文件存在
import os
file_path = 'D:/lx/study_python/iris/log.txt'
exists = os.path.exists(file_path)
if exists:
    file_object = open('D:/lx/study_python/iris/log.txt',mode = 'rt',encoding='utf-8')   #打开文件
    date = file_object.read()       #读取文件
    file_object.close()     #关闭文件
# print(date)#字符串类型:林北万岁

#写入str文件,不存在为新建
file_object = open('D:/lx/study_python/iris/log.txt',mode = 'wt',encoding='utf-8')   #打开文件
date = file_object.write('林北万岁')       #写入内容
file_object.close()     #关闭文件

对于图片,视频只能用字节来读写(其不是utf-8或gbk编码的,无法编码)

#复制,读取图片th.jpg写到thh.jpg
file_object = open('D:/lx/study_python/iris/th.jpg',mode = 'rb')   #打开文件
date = file_object.read()       #读取文件
file_object.close()     #关闭文件
# print(date)#b'\xff\xd8\xff\xe0\x00\x10JFI...
file_object = open('D:/lx/study_python/iris/thh.jpg',mode = 'wb')   #打开文件
file_object.write(date)     #写入内容
file_object.close()     #关闭文件

三、其他读文件知识补充:

file_object = open('D:/lx/study_python/iris/date.txt',mode = 'rt',encoding='utf-8')   #打开文件

# date = file_object.read(20)       #读取文件
# print(date,type(date))
# date = file_object.read(20)       #继续读取文件
# print(date,type(date))
# date = file_object.read(20)       #再次继续读取文件

# date = file_object.readline()     #读取一行

# date = file_object.readlines()    #读取每一行放入列表

for i in file_object:               #大文件循环每一行
    print(i.strip('\n'))
    
file_object.close()     #关闭文件
# print(date,type(date))#b'\xe8\xb4\xba\xe6\x9e\x97-999\r\nlll-456\r' <class 'bytes'>

四、其他写文件知识补充:

file_object = open('D:/lx/study_python/iris/log.txt',mode = 'rt+',encoding='utf-8')   #打开文件

file_object.seek(6)         #移动到指定位置
date = file_object.write('木北bei')       #写入内容
print(date)
# file_object.flush()       #立刻写入硬盘
p = file_object.tell()      #返回当前光标的位置
print(p)

file_object.close()     #关闭文件

# mode()    文件模式
# name()    文件名
# filono    内核?
# flush()   写入文件(内存到硬盘)
# readable()判断可读
# readline()读一行
# seek(n)   移动下标
# seekable()判断可移动
# tell()    当前下标
# truncate(n)截断指定长度(默认全截断)
# writeable()判断可写 

五、上下文管理器with

# file_object = open('D:/lx/study_python/iris/log.txt',mode = 'rt',encoding='utf-8')   #打开文件
# date = file_object.read()       #读取文件
# print(date)
# file_object.close()     #关闭文件

with open('D:/lx/study_python/iris/log.txt',mode = 'rt',encoding='utf-8') as file_object:
    date = file_object.read()
    print(date)

六、修改文件时的注意点

由硬盘的存储机制决定的,修改的数据只会覆盖原来的数据,并不是插入内容。(类似:创建好文件相当于一个装满东西的盒子。要把东西放进盒子,必须把原来这个位置的东西拿出来,而不能硬塞进去),如下b:

当我们打开文件修改时,计算机会将硬盘数据读到内存。可能文件数据过大,因此不能将数据完全存入内存,进而不能修改。所以我们通过A文件读一行,B文件写一行的读写方式,便可以解决问题,如下c:

#替换文件信息

#a、读到内存,使用replace替换(小文件)

with open('D:/lx/study_python/iris/bbb.conf',mode='r',encoding = 'utf-8') as ff:
    data = ff.read()#读到内存
    new = data.replace('a&
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值