1、相对路径与绝对路径比较
#绝对路径
f = open('d:\pzw.txt',mode='r',encoding='UTF-8')content = f.read()print(content)f.close()
#相对路径
f = open('pzw',mode='r',encoding='utf-8')content = f.read()print(content)f.close()
2、
#对于r就是只读
f = open('pzw',mode='rb',)content = f.read()print(content)f.close()
#对于w没有文件会创建文件,有文件会将源文件的内容全部清除再写
f = open('log',mode='w',encoding='utf-8')f.write('123456')f.close()
f = open('log',mode='wb')f.write('123456'.encode('utf-8'))f.close()
f = open('log',mode='w+',encoding='utf-8')f.write('aaa')print(f.read())f.close() #不显示任何内容
#对于a为追加功能
f = open('log',mode='a',encoding='utf-8')f.write('666')f.close()
f = open('log',mode='ab')f.write('666'.encode('utf-8'))f.close()
f = open('log',mode='a+',encoding='utf-8')f.write('666')f.seek(0)print(f.read())f.close()
3、seek用来调整光标位置,utf-8编码中文占三个字节
f.seek(3) # 是按照字节定光标的位置
4、tell用来告诉你光标的位置
f.tell() 告诉你光标的位置
5、其他
f.readable() # 是否可读line = f.readline() # 一行一行的读line = f.readlines() # 每一行当成列表中的一个元素,添加到list中
6、注册,登录
username = input('请输入你要注册的用户名:')password = input('请输入你要注册的密码:')with open('list_of_info',mode='w',encoding='utf-8') as f: f.write('{}\n{}'.format(username,password))print('恭喜您,注册成功')lis = []i = 0while i < 3: usn = input('请输入你的用户名:') pwd = input('请输入你的密码:') with open('list_of_info',mode='r+',encoding='utf-8') as f1: for line in f1: lis.append(line) if usn == lis[0].strip() and pwd == lis[1].strip(): print('登录成功') break else:print('账号和密码错误') i+=1
7、修改文件
# 修改文件with open('file',encoding='utf-8') as f,open('file.bak','w',encoding='utf-8') as f2: for line in f: if '张三' in line: #班主任:张三 line = line.replace('张三','李四') #写文件 f2.write(line) import osos.remove('file') #删除文件os.rename('file.bak','file') #重命名文件