Python 文件IO操作

1普通文件的操作:
对应计算机系统中的文件的操作,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.
打开了一个文件,得到了一个文件流对象

file is either a text or byte string giving the name (and the path
文件可以是一个给定名称的字符文件(文本文件)或者字节文件(二进制文件)

 if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)

参数处理:

e:/py1901_worksapce/
		|-- demo01.py
		|-- demo02.py
		|-- images/
			|-- default.jpg
			|-- demo03.py

文件路径【相对路径|绝对路径】
路径:文件在计算机中的位置,还可以被成为 目录/文件/文件夹
绝对路径:
demo01.py的绝对路径:e:/py1901_worksapce/demo01.py
demo02.py的绝对路径:e:/py1901_worksapce/demo02.py
相对路径:
demo01.py中查看demo02.py: ./demo02.py
查看default.jpg: ./images/default.jpg
. 表示当前路径
. . 表示父级路径
2)open()函数中的mode 参数

r (read)只读,并且默认按照读取文本文件的方式从文件中读取数据
w (write)只写,并且默认按照写入文本数据的方式将数据写入到文件中;如果多次执行程序~新数据会覆盖旧数据
a(append)追加,如果多次运行程序,新数据会追加到旧数据的后面
b(binary)-操作二进制数据-
t(text)操作文本文件
+读写方式 可以读数据 可以写数据

3)文本文件的操作:写入数据到文本文件
将程序中的数据写入到文件中

file = open(file='./date/demo01.txt', mode='w', encoding='utf-8') # 写入数据
 word = "hello 世界"
	把数据写入文本
	file. Write(word)
 关闭文件
file.close()

读取文本文件的数据到程序中

# 将文件中的数据读取到程序中
# file = open(file='./date/demo01.txt', mode='r', encoding='utf-8')
# # 从文件中读取数据 展示到控制台中
# ifo = file.read()
# print(ifo)
# # 关闭文件
# file.close()

数据文件的追加

# # 数据文件的追加
# file = open(file='./date/demo02.txt', mode='a', encoding='utf-8')
# # message = "林深不见鹿"
# message = "\n海涌不见鲸"
# file.write(message)
# file.close()
# 二进制文件的操作
# file = open(file='./date/demo02.txt', mode='rb')
# print(file.read())
# file.close()

将数据文件重新存储到指定位置

file = open(file='D:/课堂文件/a.jpg', mode='rb')
file2 = open(file='./date/b.jpg', mode='wb')
file2.write(file.read())
file2.close()
file.close()

但是每次都这么写太过于繁琐,所以Python 引入了with 语句来自动帮我们调用close()方法

with open(file='D:/课堂文件/a.jpg', mode='rb') as file1:
#     with open(file='./date/' + file1.name[file1.name.rfind('/'):], mode='wb') as file2:
#         file2.write(file1.read())

类型的转换和eval()函数:eval()函数可以自动转换数据类型

将程序中的字典数据转化成字符串存到文件中
users = {'admin': 'admin', 'password': 'admin'}
users = str(users)
with open(file='./date/demo2.1.txt', mode='w') as file:
    file.write(users)

# 将文件中的数据读取到程序中
with open(file='./date/demo2.1.txt', mode='r') as file:
    users = file.read()
    # users = dict(users)
    print(users, type(users))
    users = eval(users)
    print(users, type(users))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值