python学习笔记15-文件读写

读文件

f = open(r'F:\\test.txt')  #等价于f = open(r'F:\\test.txt','r') 'r'模式为默认值
x = f.read()
f.close()
x

'this is a test1\nthis is a test2\n'

逐行读

f = open(r'F:\\test.txt')
for line in f:
    print(line,end='')

this is a test1
this is a test2

读完文件后需要用f.close() 来关闭文件并释放系统资源,with写法可防止句体结束后文件没有被关闭

with open(r'F:\\test.txt') as f:
    for line in f:
        print(line,end='')

this is a test1
this is a test2

f.closed

True

写文件

f = open(r'F:\\test.txt','w')
f.write('this is a test3\n')
f.close()
f = open(r'F:\\test.txt')
x = f.read()
f.close()
x

'this is a test3\n'

'w'模式下原文件内容被覆盖

f = open(r'F:\\test.txt','a')
f.write('this is a test4')
f.close()
f = open(r'F:\\test.txt')
x = f.read()
f.close()
x

'this is a test3\nthis is a test4'

'a'模式下原文件内容保留,新写入的内容追加在原文件内容末尾

posted @   babysteps  阅读(142)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· 万字长文详解Text-to-SQL
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· 卧槽!C 语言宏定义原来可以玩出这些花样?高手必看!
点击右上角即可分享
微信分享提示