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表示以文本打开

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:追加写

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类型读

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.encode
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'              #光标的移动用途之一

 实例:

编写一个用户登录程序

登录成功显示欢迎页面

登录失败显示密码错误,并显示错误几次

登录三次失败后,退出程序

升级:

可以支持多个用户登录

用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态

user = 'root'
passwd = 'root'
i = 0
print("请登录:")
while True:
     new_user = input("请输入用户:")
     new_passwd = input("请输入密码:")
     if new_user == user and new_passwd == passwd:
         print("欢迎光临")
         break
     else:
         print("密码输入错误!")
         i +=1
         if i == 3:
             print("三次输入错误,退出程序")
             break