文件操作
文件操作
【一】文本处理引入
- 应用程序运行过程中产生的数据最先都是存放于内存中的
- 若想永久保存下来,必须要保存于硬盘中。应用程序若想操作硬件必须通过操作系统
- 而文件就是操作系统提供给应用程序来操作硬盘的虚拟概念
- 用户或应用程序对文件的操作,就是向操作系统发起调用,然后由操作系统完成对硬盘的具体操作。
【二】文件的操作模式
【1】文件的操作模式
- r(默认的):
- 只读
- w:
- 只写
- a:
- 只追加写
# 写文件 w
# w(write) 模式 : write 覆盖写模式,如果你文件中有内容,直接覆盖掉写进去新的内容
# 如果不存在该文件,则会创建一个新的文件,然后再向文件中写新的内容进去
# -with
with open('01.txt', 'w', encoding='utf-8') as f:
f.write('my name is dhy')
# 读文件 r
# r(read) 模式 : read 读内容模式,可以将文件中的内容读出来
with open('01.txt', 'r', encoding='utf-8') as f:
data = f.read()
print(data)
# a(append) 模式 : write 追加写模式,如果你文件中有内容,再原有内容的基础上追加内容
# 如果不存在该文件,则会创建一个新的文件,然后再向文件中写新的内容进去
# 追加 a
with open('01.txt', 'a', encoding='utf-8') as f:
f.write('\n'+'my age is 20')
# 注册
username = input('输入用户名:>>>>')
password = input('输入密码:>>>>')
user_data = f'{username}-{password}'
with open('02.txt', 'a', encoding='utf-8') as f:
f.write(user_data + '\n')
# 登录
with open('02.txt', 'r', encoding='utf-8') as f:
data = f.read()
for data in data.split('\n'):
if bool(data):
username_old, password_old = data.split('-')
username = input('输入用户名:>>>>')
password = input('输入密码:>>>>')
if username == username_old and password_old == password:
print(f'{username}登陆成功')
break
else:
pass
【2】控制文件读写内容的模式
- tb模式均不能单独使用,必须与r/w/a之一结合使用
t:文本模式
- 读写文件都是以字符串为单位的
- 只能针对文本文件
- 必须指定encoding参数
# t 模式 : 文本类型。读内容和写内容都是字符串格式
import os
# # 获取当前文件路径
file_path = os.path.abspath(__file__)
print(file_path)
# wt
with open('01.txt', 'wt', encoding='utf-8') as f:
f.write('今天天气很好')
# # rt
with open('01.txt', 'rt', encoding='utf-8') as f:
data = f.read()
print(data, type(data))
# 今天天气很好 <class 'str'>
# at
with open('01.txt', 'at', encoding='utf-8') as f:
f.write('dhy')
# 今天天气很好dhy
b:二进制模式
- 读写文件都是以bytes/二进制为单位的
- 可以针对所有文件
- 一定不能指定encoding参数
import requests
response = requests.get(
'https://t7.baidu.com/it/u=2397542458,3133539061&fm=193&f=GIF')
data = response.content
with open('1.jpg', 'wb') as f:
f.write(data)
with open('1.jpg', 'rb') as f:
data = f.read()
print(data)
文件拷贝练习
src=input(r'源文件路径:F:\shanghai\day09\01.txt ').strip()
dst=input(r'目标文件路径:F:\shanghai\day09\img\1.txt ').strip()
with open(r'%s' %src,mode='rb') as read_f,open(r'%s' %dst,mode='wb') as write_f:
for line in read_f:
# print(line)
write_f.write(line)
【三】操作文件的方法
【1】读操作
f.readline()
-
读取一行内容,光标移动到第二行首部
-
with open('01.txt', 'r', encoding='utf-8') as f: dhy = f.readline() print(dhy)
f.readlines()
- 读取每一行内容,存放于列表中
with open('01.txt', 'r', encoding='utf-8') as f:
data = f.readlines()
print(data)
【2】写操作
-
f.write()
- 一次性全部写入
with open('02.txt', 'w', encoding='utf-8') as f: f.write('天气好') -
f.writelines()
- 可以迭代写入可迭代对象内的内容
with open('02.txt', 'w', encoding='utf-8') as f: f.writelines(['dhy', 'ddddhy']) # dhyddddhy -
write方法

浙公网安备 33010602011771号