day007 迈向大神之路---文件

文件操作

小知识

  • 文件路径
    绝对路径 从原始到目的
    相对路径 当前运行的文件路径
  • 编码方式
  • 操作方式 只读 只写 读写 写读…

以什么编码储存 就以什么打开文件读取

1.读取 只读:r rb(不应编码打开 非文字类)

#读取的操作
f=open('d:\1.txt',mode='r',encoding='utf-8')   #以绝对路径打开
f=open('1.txt',mode='r',encoding='utf-8')#以相对路径打开
content=f.read()  
print(content)
f.close()

2.只写: w wb 没有此文件 就会创建此文件 (覆盖)

#写入文件
  f=open('125',mode='w',encoding='utf-8')
  f.write("高崎")
  f.close()
#写入二进制文件
   f=open('125',mode='wb')
   f.write("hello".encode('utf-8')) #以utf-8写入
   f.close()

3. 追加 a ab

f=open('125',mode='a',encoding='uttf-8')
f.write("wangzhen")
f.close()

f=open('125',mode='ab')
f.write("wangzhen".encode('utf-8'))
f.close()

4. 读写 r+b 先读后写


+号多种操作不会报错

f=open(‘125’,mode=‘r+’,encoding=‘uttf-8’) #(# 常用r+)

f.read()
f.write()
f.close()
只能进行2步 指的是 f.read() 和f.write()才做

mode 从某种方式是开始读的行数 +号多种操作不会报错
f.write(‘aaaa’)
f.seek(0)

print(f.read()) #会不显示 因为光标移到最后面了
f.close()

5. 写读 w+b

f=open(‘125’,mode=‘w+’,encoding=‘utf-8’)

其他方式(补充)

read 字符

  1. read(3) #只读3个字符 对出来的都是字符
  2. f.seek() #按照字节找的 1个中文字符3个字节 f.seek(count-3)
  3. f.tell() #光标在哪 断点续传 按照字节找的 1个中文字符3个字节
  4. f.readable() 是否可读
  5. f.readline() #按照行读取
  6. f.readlines() #每一行当成列表中的一个元素
  7. f.truncate(1,2) #源文件截取
    读取方式:
    for line in f: #一行一行读
    print(line)
    f.close()
with open('125',mode='r+',encoding='uttf-8') as obj:
	print(obj.read())    #文件自动关闭    @!!!有缩进

#可以同时打开2个文件  并进行操作(常用)
with open('125',mode='r+',encoding='uttf-8') as obj, open('125',mode='w+',encoding='uttf-8') as f1:
	print(obj.read())   #有缩进

ps 案列 注册+账号密码与文件匹配(输入3次 失败)

# username=input("请输入你的名字")
# passwd=input("请输入你的密码")
# with open('info',mode='w+',encoding='utf-8') as f:
#     f.write('{}\n{}'.format(username,passwd))
# print("恭喜你注册成功!")
lis=[]
i=0
while i < 3 :
    uname = input("请输入你的名字")
    pwd = input("请输入你的密码")
    with open('info', mode='r+', encoding='utf-8') as f1:
        for line in f1:
            lis.append(line)
    if uname==lis[0].strip() and pwd==lis[1].strip():
        print("登录成功")
        break
    else:
        print("请输入正确的密码")
    i+=1

编码之间相互转换

str —>byte encode 编码
s = ‘二哥’
b = s.encode(‘utf-8’)
print(b)

#byte —>str decode 解码
s1 = b.decode(‘utf-8’)
print(s1)

#byte —>str encode 编码
s = ‘abf’
b = s.encode(‘utf-8’)
print(b)

#byte —>str decode 解码
s1 = b.decode(‘gbk’)
print(s1)

猜你喜欢

转载自blog.csdn.net/qq_35131055/article/details/83115232