7天学习—day4—Python的文件读写操作

YU. AN YU. AN 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

1.open函数的使用

2.读取方式

 

ps:读取txt格式的文件,要注意补充 

encoding = 'utf-8'

不然会报错。

4.其他练习

# 使用 with 运算符
with open("test.txt") as file_handler:
    for line in file_handler:
        print(line)

# 捕捉异常
try:
    file_handler = open("test.txt")
    for line in file_handler:
        print(line)
except IOError:
    print("An IOError has occurred!")
finally:
    file_handler.close()

# 使用with来做同样的事情
try:
    with open("test.txt") as file_handler:
        for line in file_handler:
            print(line)
except IOError:
    print("An IOError has occurred!")

 

...全文
评论
收藏 已收藏
分享
返回顶部
YU. AN
Python全栈技术社区 12,068 成员 3,314 内容