当前位置: 移动技术网 > IT编程>脚本编程>Python > day8 文件操作

day8 文件操作

2018年09月12日  | 移动技术网IT编程  | 我要评论

什么叫一线品牌,噤若寒蝉造句,白岩松照顾瘫痪妻子

一、文件操作

  • r
1 f=open('log',mode='r',encoding='utf-8')
2 a=f.read()
3 print(a)
4 f.close()
  • rb
1 f=open('log',mode='rb')  #已bytes类型输入,不需要encoding='utf-8'
2 a=f.read()
3 print(a)
4 f.close()
  • w
1 f=open('log',mode='w',encoding='utf-8')  #w操作会将文件中原来的内容覆盖掉
2 a=f.write("你好")
3 f.close()
  • wb
1 1 f=open('log',mode='wb')
2 2 a=f.write("菜菜")     #typeerror: a bytes-like object is required, not 'str'
3 3 f.close()
4 
5 #修改后
6 f=open('log',mode='wb')
7 a=f.write("菜菜".encode('utf-8'))      #需要进行转码,因为是用bytes类型传入
8 f.close()
  •  a
1 f=open('log',mode='a',encoding='utf-8')
2 f.write(',你今天真好看啊')           #追加的内容不会覆盖文件内之前得内容
3 f.close()
  • ab
1 f=open('log',mode='ab')
2 f.write('\n你可真讨厌啊,邓晓灵'.encode('utf-8'))
3 f.close()
  •  r+
1 f=open('log',mode='r+',encoding='utf-8')
2 print(f.read())
3 f.write('\n皮皮你真可爱啊')
4 print(f.read())    #读写模式下这一步不会被系统执行
5 f.close()
  •  w+
1 f=open('log','w+',encoding='utf-8')
2 f.write("妞妞你真讨厌啊")
3 print(f.read())   #写读模式下,这句也不会执行,因为光标现在在最后
4 f.close()

二、文件常用操作

 1 f=open('log','r+',encoding='utf-8')
 2 
 3 #read() :方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。
 4 a=f.read(3)  #read按照字符来进行读写
 5 print(a)
 6 
 7 #seek() 方法用于移动文件读取指针到指定位置。
 8 f.seek(3)  #seek是按照字节来寻找的,在utf-8中一个中文字符占3个字节,一个英文字母占一个字节
 9 a=f.read()
10 print(a)
11 
12 #tell() 方法返回文件的当前位置,即文件指针当前位置。
13 a=f.tell()
14 print(a)
15 
16 #readable()方法判断文件是否可读
17 a=f.readable()
18 print(a)
19 
20 #readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。
21 a=f.readline()  #一行行的读,如果不加参数只会读取第一行
22 print(a)
23 
24 #readlines() 方法用于读取所有行(直到结束符 eof)并返回列表,该列表可以由 python 的 for... in ... 结构进行处理。
25 a=f.readlines()  #读出来为列表
26 print(a)
27 
28 #truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。
29 f.truncate(6)  #在utf-8中一个中文字符占3个字节,如果后面参数不为3的悲伤,截取出来的中文就会处出现问题。
30 
31 f.close()

 三、with:为了避免打开文件后忘记关闭,可以通过管理上下文

 1 with open('log','r') as f: 2 f.readlines() 

四、作业

要求:先进行注册,在登录。

 1 username = input('请输入你要注册的用户名:')
 2 password = input('请输入你要注册的密码:')
 3 with open('list_of_info',mode='w',encoding='utf-8') as f:
 4     f.write('{}\n{}'.format(username,password))
 5 print('恭喜您,注册成功')
 6 lis = []
 7 i = 0
 8 while i < 3:
 9     usn = input('请输入你的用户名:')
10     pwd = input('请输入你的密码:')
11     with open('list_of_info',mode='r+',encoding='utf-8') as f1:
12         for line in f1:
13             lis.append(line)
14 
15     if usn == lis[0].strip() and pwd == lis[1].strip():
16         print('登录成功')
17         break
18     else:print('账号和密码错误')
19     i+=1

 

 

 

  

 

    

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网