IO 编程初识
IO编程中,Stream(流)是一个很重要的概念,可以把流想象成一个水管,数据就是水管里的水,但是只能单向流动。Input Stream就是数据从外面(磁盘、网络)流进内存,Output Stream就是数据从内存流到外面去。对于浏览网页来说,浏览器和新浪服务器之间至少需要建立两根水管,才可以既能发数据,又能收数据。
读文件 read()
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 读文件 open
# 读取文件
def openFile():
try:
f = open("D:/PythonProject/Hello.txt", "r")
print(f.read())
except Exception as e:
print(e)
finally:
if f:
f.close()
运行结果
===================== RESTART: D:\PythonProject\main.py =====================
Hello world
>>>
with 语句
Python 的with 语句,作用自动调用close()方法
示例
# 更加简洁的读文件方法
def bestOpenFile():
# Python 的with 语句,作用自动调用close()方法
with open("D:/PythonProject/Hello.txt", "r") as f:
print(f.read())
readlines
按行读文件
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 读文件 open
# 按读取文件
def readFile():
# 设置编码的文本文件
f = open("D:/PythonProject/Hello.txt", "r", encoding = "utf-8")
for line in f.readlines():
print(line)
# 运行方法
def runTest():
readFile();
# 运行
runTest()
运行结果
===================== RESTART: D:\PythonProject\main.py =====================
Hello world
My name is lilei
>>>
写文件 write
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 写文件 write
def writeFile():
# 文件位置
# 写权限
# 编码方式
with open("D:/PythonProject/Hello.txt","w",encoding = "utf-8") as f:
f.write("写文件 write q_q")
with open("D:/PythonProject/Hello.txt","r",encoding = "utf-8") as f:
for line in f.readlines():
print(line)
# 运行方法
def runTest():
writeFile()
# 运行
runTest()
运行结果
===================== RESTART: D:\PythonProject\main.py =====================
写文件 write q_q
>>>