Python基础-IO编程-读文件read-写文件write

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
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值