python学习笔记-day6

python文件操作

对文件的操作有2种,文本文件、二进制文件(视频,图片)

open方法基本使用

open(file,mode = 'r',encoding = None)

几种打开模式:

'r': 只读模式
'w':写模式,如果文件在,先清空 危险!
'x':创建模式,如果文件在,会报错
'a':类似日志
'b':二进制模式
't':文本模式
'+':r+w

⼀个⽂件对象被open⽅法创建后,这个对象可⽤的有下⾯这些

close 关闭⽂件
closed 查看⽂件是否已关闭
encoding 返回⽂件的编码
flush 把缓存⾥的写⼊的数据强制刷新硬盘
isatty 返回⽂件是否是'interactive'数据流,⽐如是个命令⾏终端,(在unix系统,⼀切皆⽂件)
mode 返回当前⽂件模式
name 返回⽂件名
read 读指定⻓度的内容,f.read(1024) 读1024字节, 不指定参数的话,就读所有内容
readable ⽂件是否可读
readline 读⼀⾏
readlines 读所有,每⾏列表形式返回
seek 把光标移到指定位置
seekable 该⽂件光标是否可移动
tell 返回当前光标位置
truncate 截断⽂件, f.truncate(100), 从⽂件 开头截断100个字符,后边的都扔掉
writable 是否可写

创建模式:创建文件

f = open("contacts.txt", 'w') # 创建⼀个⽂件对象(⽂件句柄),存为变量f f.write("alex 133332") # 写⼊
f.close() # 关闭这个⽂件
f.write('dddd') # 关闭后,没办法再写⼊了

按⾏读取&循环:

f = open("model_contacts.txt") # 默认`rt`模式
print(f.readline()) # 读第1⾏
print(f.readline()) # 读第2⾏
print(f.readline()) # 读第3⾏
print('----循环读后⾯的-----')
for line in f:
 print(f.readline())

⽂件⾥查找内容:

f = open("model_contacts.txt")
for line in f:
 if "梦⽵" in line:
 print(line)

运算符

公共方法

推导式

列表推导式: 返回列表

list1 = [i for i in range(10)]
print(list1)
#带if的列表推导式
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)
# 多个for循环实现列表推导式 [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list1 = [(i, j) for i in range(1, 3) for j in range(3)]
print(list1)

字典推导式:返回字典

dict1 = {i: i**2 for i in range(1, 5)}
print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}
#将两个列表合并为⼀个字典
list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
dict1 = {list1[i]: list2[i] for i in range(len(list1))}
print(dict1)
# 提取字典中⽬标数据
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
# 需求:提取上述电脑数量⼤于等于200的字典数据
count1 = {key: value for key, value in counts.items() if value >= 200}
print(count1) # {'MBP': 268, 'DELL': 201}

集合推导式:返回集合

list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1) # {1, 4}

推导式总结

# 列表推导式
[xx for xx in range()]
# 字典推导式
{xx1: xx2 for ... in ...}
# 集合推导式
{xx for xx in ...}

引用

在python中,值是靠引用来传递的
可以用id()来判断两个变量是否为同一值的引用

可变和不可变类型

可变类型:
列表
字典
集合
不可变类型:
整型
浮点型
字符串
元组

原文地址:https://www.cnblogs.com/liuChang888/p/15038674.html