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

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

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

#读取文件
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!")

 

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部