四. 数据类型:其它类型 + 文件

空对象 None

布尔 bool:True、False
True本质为 1(等且只等于),False本质为0(等且只等于)。
True + 4 -> 5
False – 3 -> -3
注意:
bool(3) -> True
bool(-3) -> True
bool(0) -> False
bool(‘s’) -> True
bool([]) -> False
bool(‘’) -> False
真值测试:数字0或0.0,None,空对象([],’’),空的映射返回False

文件

open(‘路径’,模式’’,encoding=’编码’)

路径:

r’D:\GitRepositories\Pictures\BlogSystem’ 或
’D:\GitRepositories\Pictures\BlogSystem’

模式:

  • ‘r’:读
  • ‘w’:写
  • ‘rw’:读写
  • ‘a’:追加
  • 二进制 ‘*b’:r,w,rw或a后加b。

f.read() 读取全部内容
f.close() 关闭
f.seek(0) 移动读取指正到指定位置

文本文件读/写

f.read(4) 读取4个字符(字节)
f.readlines() 读取所有行到列表
f.readline() 读取下一行
for line in file 直接迭代遍历

cs.write(‘啊打发\naa’)
cs.flush() 同步到文件
cs.close() 同步并关闭文件
cs.readlines([‘a’,’b’]) 一次写入多个元素

name = [‘a’,’b’,’c’]
n = [n + ‘\n’ for n in name] -> [‘a\n’,’b\n’,’c\n’] 从已有类别中创建新列表

上下文代码体,上下文对象 f,最后f会自动关闭(无需显示调用f.close())。

with open(‘’) as f:
for line in f:
    print(line)
发布了110 篇原创文章 · 获赞 50 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/aimeimeiTS/article/details/85005102