python文件操作
2022/2/8 9:42:37
本文主要是介绍python文件操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文件操作(数据库第一天)
引入
什么是文件:
文件是保存在持久化存储设备上的一段数据。
文件分类:
文本文件
二进制文件
字节串类型:
字节串与str不同,字节串以字节序列值表达数值,更方便用来处理二进制数据。
字节串和字符串相互转化:
-普通的英文字符串可以通过前面加b来转换成字节串:b"hello"
-变量或包含非英文的字符串转换成字节串方法:str.encode()
-字节串转换成字符串方法:bytes.decode()
注意:所有的字符串都可以转换成字节串,但不是所有的字节串都能转成字符串。
文件读写操作
读:从文件中读取数据
写:向文件中写入数据
打开文件,写入数据,关闭文件。
打开文件
如果不确定文件类型,就是用二进制方式打开,也就是wb+ file_object=open(filename,mode,buffering,encoding=None) 成功返回一个文件对象。 filename:文件名 mode:打开文件方式 buffering:1 行缓冲,默认 默认缓冲 encoding="UTF-8:文件编码方式 mode:r,w,a,r+,w+,a+,rb,wb,ab,rb+,wb+,ab+ r:读方式打开,文件需要存在 w:写方式打开,文件不存在则创建,存在清空原有内容 a:追加模式,不存在创建,存在则续写 r+:读写模式打开,文件必须存在 w+:读写模式打开,不存在创建,存在清空原有内容 a+:追加并可读模式,不存在创建,存在续写 rb:二进制读模式 wb:二进制写模式 ab:二进制追加 纯r的话需要文件存在,w如果文件不存在则创建,否则清空。 如果要续写的话还是使用a 二进制模式都加一个b,增强读写模式增加一个+ 以二进制方式打开的话,读取的是字节串。需要进行decode 以二进制方式写入,写入的需要是字节串,可以在前面加b,或者encode。
关闭文件
file_object.close()
print(,end="")# end打印完前面后的操作,可以进行不换行。
循环读取文件
# 循环读取文件 file = open("file.txt", 'r') while True: message = file.read(1) if not message: break print(message, end="") file.close()
readlines(size)
按行读取
迭代取值
当使用读方式打开文件时,该文件是可迭代对象,可以通过
for line in file:
print(line,end="")
来进行读取按行输出。
复制
# 复制 src = open("file.txt", "rb+") dst = open("dst.txt", "wb+") for line in src: dst.write(line) dst.close() src.close()
查字典
# 练习1:使用dict.txt完成,查询单词,返回解释,否则返回Not Found def search(key): # 通过key查询单词是否在其中 file = open("dict.txt", "rb+") dict = {} for line in file: line = line.decode() list = line.split(" ", 1) if list[0] > key: break elif list[0] == key: return line.strip() return 'Not Found' while True: key = input("输入单词:") message = search(key) print(message)
文件偏移量
file.tell()
获取文件偏移量
seek(offset[,whencel])
移动文件偏移量位置
offset 代表相对于某个位置移动的字节数。负数表示向前移动,正数表示向后移动。
whence 是基准位置的默认值为0,代表从文件开头算起,1代表当前位置,2代表从文件末尾。(二进制模式)
空洞文件
文件开头写入,改变偏移量,然后文件末尾写入,预占容量。
file.seek(1024*1024,2)
file.write(b'end')
时间
time()
localtime()
ctime()
文件每2s循环写入,序号可以衔接
# 首先打开文件,查看最后的序号是多少, # 然后从该序号后开始依次加1,写入文件ctime。 import time # 打开文件 file = open('time.txt', 'rb+') for line in file: line = line.decode() list = line.split('.') n = int(list[0]) try: i = n except Exception: i = 0 while True: i += 1 message = f"{i}. {time.ctime()}" file.write(message.encode()) file.write(b"\n") time.sleep(2) file.flush()
或者
import time # 打开文件 file = open('time.txt', 'rb+') i = len(file.readlines()) while True: i += 1 message = f"{i}. {time.ctime()}" file.write(message.encode()) file.write(b"\n") time.sleep(2) file.flush()
os模块
Python标准库模块,包含了大量的文件处理函数
os.path.getsize(file)
获取文件大小,参数指定文件,返回值返回文件大小。
查看文件列表
os.listdir()
判断文件是否存在 bool
os.path.exists(file)
删除文件
os.remove(file)
总结:
open()
read()
write()
close()
文件拷贝
这篇关于python文件操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础