一.文件基本操作
1.文件的打开
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作
文件句柄 = open('文件路径', '模式')
2.文件的读取
>>> f = open("f:/test.txt", "r")
>>> f.read()
'hello,world'
>>> f.close
3.打开文件的模式有:
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容;】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
>>> f = open("f:/test.txt", 'r+')
>>> f.read()
'heheo,world~~'
>>> f.write("\naaaaaaa")
8
>>> f.tell()
22
>>> f.read()
''
>>> f.tell()
22
>>> f.seek(0)
0
>>> f.read()
'heheo,world~~\naaaaaaa'
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
#以二进制文件写
f = open("file.txt", "wb")
str_data = "呵呵"
bytes_data = bytes(str_data, encoding='utf-8')
f.write(bytes_data)
f.close()
#以二进制文件读
f = open("file.txt",'rb')
data = f.read()
f.close()
print(data)
str_data = str(data,encoding="utf-8")
print(str_data)
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
4. r+, w+, x+, a+ 区别
r+ 可读,可写,若文件不存在会报错,根据指针位置可写随意位置
w+ 可写,可读,若文件不存在会创建,在进行写操作会清空文件内容
x+ 可写,可读,若文件存在会报错,不存在则创建
a+ 可写,可读,只能追加在文件尾部
5.文件内部支持操作:
readline() 逐行读取数据
#逐行去读,较省内存
f = open('log','r')
result = list()
for line in open('log'):
line = f.readline()
print(line)
result.append(line)
print(result)
f.close()
trancate(),从文件的首行首字符开始截断,截断文件为n个字符;无n表示从当前位置起截断;截断之后n后面的所有字符被删除
>>> with open("f:/test.txt" , 'r+') as f:
... f.seek(2)
... f.truncate(3)
...
2
3
>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
...
'hel'
read(),读取文件内容
>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
...
'hel'
write(),写入内容
>>> with open("f:/test.txt" , 'r+') as f:
... f.read()
... f.write('llo' + '\n' + 'test')
... f.seek(0)
... f.read()
...
'hel'
8
0
'helllo\ntest'
readlines(), 将文件内容以列表的形式存放,---->[“第一行”, "第二行"]
>>> with open("f:/test.txt" , 'r+') as f:
... temp = f.readlines()
... print(temp)
...
['heheo,world~~\n', 'aaaaaaa']
open(),打开文件
>>> f = open('f:/test.txt', 'r')
close(),关闭文件
flush(),强行刷入硬盘
tell() 获取指针位置
seek() 跳转到某个位置
二.管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文
with open("log", 'r+') as f:
data = f.read()
print(data)
三.练习
编写脚本实现 ,用户登录,注册,改密,删除功能
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#删除用户,修改密码
def login(username, password):
"""
用户登录验证
:param username: 用户名
:param password: 密码
:return: True成功,False失败
"""
f = open('log', 'r', encoding='utf-8')
for line in f:
line = line.strip()
userlist = line.split('$')
if username == userlist[0] and password == userlist[1]:
return True
return False
def user_ex(username):
"""
用于检测用户是否存在
:param username: 用户名
:return: True 表示存在,False用户不存在
"""
with open('log','r',encoding='utf-8') as f:
fo