高进

python文件操作和os模块

好久不见. 提交于 2020-03-02 21:36:00
文件操作 读取文件 语法: open(file,mode) mode 释义 r read 读 w weite 写 b binary 二进制 read() 读取所有内容 mode默认是rt,文本文件 如果文件找不到会报错 stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt') container = stream.read() print(container) 11111 22222 33333 readline() 每次读取一行内容 stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt') while True: container = stream.readline() print(container,end='') if not container: break 11111 22222 33333 默认读取每行都会有一个回车,所以将每次打印后的回车取消 readlines() 读取所有的行保存到列表中 stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt') lines = stream.readlines() print(lines) ['11111\n', '22222\n', '33333']