11,073
社区成员
发帖
与我相关
我的任务
分享
总结:整体来说,今天任务不难,代码见下面
#读取文件
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!")