初识python-day3之文件操作

课堂笔记:

一、文件读写基本使用

# 对文本进行操作
# open(参数1: 文件的绝对路径/文件的名字,参数2:操作模式, 参数3: 指定字符编码)
# f: 称之为 句柄
# r: 避免转义符

# 打开文件会产生两种资源,一种是python解释器与python文件的资源,程序结束python会自动回收。
# 另一种是操作系统打开文件的资源,文件打开后,操作系统并不会帮我们自动收回,所以需要手动回收资源。

1、 写文件
f = open(
r'/python相关/python_files/安徽工程/files/文件的名字.txt',
mode="wt",
encoding="utf-8")

f.write('hello 安徽工程大学')

f.close()

2、读文件
f = open(
r'/python相关/python_files/安徽工程/files/文件的名字.txt',
'r', # 默认rt
encoding='utf-8')

res = f.read()
print(res)
f.close()


3、文件追加模式 a
f = open(r'/python相关/python_files/安徽工程/files/文件的名字.txt',
'a', # 默认at模式
encoding='utf-8'
)

f.write('\nhello jason')

f.close()

二、文件处理之上下文管理: with

# with会自带close()功能,
# 会在文件处理完以后自动调用close()关闭文件

1、写文件
with open(r'file1.txt', 'w', encoding='utf-8') as f:
f.write('life is short, u need python!')


2、读文件
with open(r'file1.txt', 'r', encoding='utf-8') as f:
res = f.read()
print(res)

3、文件追加
with open(r'file1.txt', 'a', encoding='utf-8') as f:
f.write('\n AAA')

三、图片与视频读写操作

# import requests # pip3 install requests
# res = requests.get(
# '某网站.jpg')
# print(res.content)
#
1、写入图片
# with open('大帅比.jpg', 'wb') as f:
# f.write(res.content)
#
#
2、读取图片
# with open('大帅比.jpg', 'rb') as f:
# res = f.read()
# print(res)
#
#
3、文件拷贝操作
# with open('大帅比.jpg', 'rb') as f, open('小哥哥.jpg', 'wb') as w:
# res = f.read()
# w.write(res)
#
#

4、读写视频
# with open('tianyan_sys.mp4', 'rb') as f, open('tianyan_sys_copy.mp4', 'wb') as w:
# res = f.read()
# print(res)
# w.write(res)


5、一行一行读文件
# with open('tianyan_sys.mp4', 'rb') as f, open('tianyan_sys_copy.mp4', 'wb') as w:

# 一次打开文件所有内容,若文件的大小超出内存的大小会导致内存溢出
# f.read()

# 一行一行读取文件内容,一行一行写入文件中,避免内存溢出
# for line in f:
# w.write(line)

# res = f.read()
# print(res)
# w.write(res)
 
 

猜你喜欢

转载自www.cnblogs.com/lweiser/p/11020458.html