python文件的基本操做

打开文件的三种方式:
  open(r'E:\学习日记\python\code\文件的简单操做.py')
  open('E:\\学习日记\\python\\code\\文件的简单操做.py')
  open('E:/学习日记/python/code/文件的简单操做.py')
#字符串前面加一个r表明原生的raw
# rt,wt,at:r读,w、a写,t表示以文本打开python

eg:
>>> res = open(r'E:\test.txt','r',encoding='utf-8')
>>> read = res.read()
>>> print(read)
>>> res.close()
123
小米
qwe
asd

#文本形式读取学习

with open(r'E:\test.txt','rt',encoding='utf-8') as f:

#read(1)表明读取一个字符,读取光标往右的内容(默认光标在开头)
  data1 = f.read(1)
  print(data1)
  data2 = f.read(1)
  print(data2)
1
2

#readline:按行读取
  data1 = f.readline()
  data2 = f.readline()
  print(data1)
  print(data2)
123
小米

#readlines:把内容以列表形式显示
  data = f.readlines()
  print(data)
['123\n', '小米\n', 'qwe\n', 'asd']
  for a in data:
  print(a)
123

小米

qwe

asd

#readable:是否可读(返回布尔类型)
  res = f.readable()
  print(res)
True

#文本形式写
#w:覆盖写
#a:追加写ui

with open(r'E:\test.txt','wt',encoding='utf-8') as res:
#write:往文件里覆盖写入内容
  res.write('谢谢你的爱1999')
谢谢你的爱1999(test.txt)

#writelines:传入可迭代对象变成字符串写入文件
  res.writelines(['qw','\n12','3er'])
  res.writelines({'name':'小米','age':23})
helloqw
123ernameage

with open(r'E:\test.txt','at',encoding='utf-8') as res:
#a模式write写入为追加
  res.write('\n456')
helloqw
123ernameage
456

#writable:是否可写
  res.writable()
True 

#rb,wb,ab
#bytes类型读spa

with open(r'E:\test.txt','rb') as res:
  a = res.read()
  print(a)
b'hello\r\n\xe4\xbd\xa0\xe5\xa5\xbd'
  print(a.decode('utf-8'))
  hello
你好

# bytes类型写:
#1.字符串前面加b(不支持中文)
# 2.encodecode

with open(r'E:\test.txt', 'wb') as res:
  res.write(b'asd')
asd
  res.write('你好'.encode('utf-8'))
你好 

#光标的移动对象

with open(r'E:\test.txt', 'wb') as res:
#前面的数字表明移动的字符或字节,后面的数字表明模式(0:光标在开头,1:表明相对位置,2:表明光标在末尾)
  res.seek(2,0)
  print(res.read())
e
qwertyuiop
  res.seek(1,0)
  res.seek(2,1)
  print(res.read().decode('utf-8'))
qwertyuiop
  res.seek(-3,2)
  print(res.read().decode('utf-8'))
iop 

# tail -f /var/log/message | grep '404'blog

小练习: utf-8

  # 编写一个用户登陆程序
   登陆成功显示欢迎页面
   登陆失败显示密码错误,并显示错误几回
   登陆三次失败后,退出程序字符串

 做业升级:
   # 能够支持多个用户登陆
   # 用户3次认证失败后,退出程序,再次启动程序尝试登陆时,仍是锁定状态it

相关文章
相关标签/搜索