11,846
社区成员




# handle = open("test.txt")
print(r"D:\pytest\code\test.txt")
print("D:\pytest\code\test.txt")
handle = open("D:/pytest/code/test.txt", "r")
data = handle.read()
print(data)
handle.close()
handle = open("D:/pytest/code/test.txt", "r")
data = handle.readline() # 只读取一行
print(data)
data = handle.readlines() # 读取所有行
print(data)
handle.close()
# 分块读取
handle = open('test.txt', 'r')
for line in handle:
print(line)
handle.close()
handle = open('test.txt', 'r')
while True:
data = handle.read(1024)
print(data)
if not data:
break
# 读取二进制
#handle = open('day01.ipynb', 'rb')
# 写文件
handle = open('test.txt', 'w')
handle.write("这是一个测试!")
handle.close()
# 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()
以上是代码
以下是运行结果
text.txt
h
e
l
l
o