七天学习-day4-用python读写文件

变瘦的鹏少 7天学习优秀学员 2021-09-20 17:30:32

总结:整体来说,今天任务不难,代码见下面

#读取文件
handle = open(r"C:\Users\wp\Desktop\test.txt", "r")
print("***************************************************")

#读取文件内容
handle1 = open(r"C:\Users\wp\Desktop\test.txt", "r")
data = handle1.read()
print(data)
handle1.close()
print("***************************************************")
#只读第一行
handle2 = open(r"C:\Users\wp\Desktop\test.txt", "r")
data = handle2.readline()  # 只读取一行
print(data)
handle2.close()
print("***************************************************")
#读取所有行
handle3 = open(r"C:\Users\wp\Desktop\test.txt", "r")
data = handle3.readlines()  # 读取所有行!
print(data)
handle3.close()
print("***************************************************")
#分块读取文件
handle4 = open(r"C:\Users\wp\Desktop\test.txt", "r")
for line in handle4:
    print(line)

handle4.close()
print("***************************************************")
#
handle5 = open(r"C:\Users\wp\Desktop\test.txt", "r")

while True:
    data = handle5.read(1024)
    print(data)
    if not data:
        break


print("***************************************************")
#handle6 = open("test.pdf", "rb")
handle7 = open(r"C:\Users\wp\Desktop\test.txt", "w")
handle7.write("这是一个测试!")
handle7.close()

with open(r"C:\Users\wp\Desktop\test.txt") as file_handler:
    for line in file_handler:
        print(line)
handle = open(r"C:\Users\wp\Desktop\test.txt")

try:
    file_handler = open(r"C:\Users\wp\Desktop\test.txt")
    for line in file_handler:
        print(line)
except IOError:
    print("An IOError has occurred!")
finally:
    file_handler.close()

try:
    with open(r"C:\Users\wp\Desktop\test.txt") as file_handler:
        for line in file_handler:
            print(line)
except IOError:
    print("An IOError has occurred!")

 

...全文
244 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

11,073

社区成员

发帖
与我相关
我的任务
社区描述
创建由Python学习者和社区专家组成的国内最大的第三方Python中文社区,帮助社区成员更好地入门学习、职业成长和应用实践
python学习 企业社区
社区管理员
  • Python全栈技术社区
  • Lumos_zbj
  • 北侠大卫
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

创建由Python学习者和社区专家组成的国内最大的第三方Python中文社区,帮助社区成员更好地入门学习、职业成长和应用实践

  • 这里有最新最全的 Python 学习内容及资源,每月多达4次技术公开课
  • 这里有众多 Python 学习者,陪伴你一起交流成长
  • 这里有专业 Python 社区专家、讲师,帮助你跨越学习瓶颈,解决实操难题
  • 这里有丰富的社区活动,可以开阔眼界,结识更多同伴

【最新活动】:

  1. 周四技术公开课讲师招募中,点击查看详情
  2. “Python 社区专家团” 招募中,点击查看详情

 

试试用AI创作助手写篇文章吧