Python文件操作
2022/6/28 14:20:34
本文主要是介绍Python文件操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
读取文件
#打开文件 file_object = open('info.txt', mode="rb") #读取文件内容,保存到变量 data = file_object.read() #关闭文件 file_object.close() data = data.decode("utf-8") print(data)
读取文件步骤:
- 打开文件
- 读取文件内容,保存到变量
- 关闭文件
注意:操作完的文件一定记得关闭
读取图片的非文本文件
png = open('./1.png', mode="rb") data = png.read() png.close() print(data)
文件不存在判断
import os file_path = "./1.png" exists = os.path.exists(file_path) if exists: file_obj = open('./1.png', mode = 'rb') data = file_obj.read() file_obj.close() print(data) else: print('文件不存在')
写文件
写文本文件
file_obj = open('info.txt', mode='wb') file_obj.write("你好".encode("utf-8")) file_obj.close()
file_object = open("t1.txt", mode='wt', encoding='utf-8') #必须指定编码 file_object.write("武沛齐") file_object.close()
写图片等文件
file_obj = open('./1.png', mode="rb") content = file_obj.read() file_obj.close() file_obj = open('./2.png', mode='wb') file_obj.write(content) file_obj.close()
这篇关于Python文件操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python
- 2024-03-12python colon equals