with open("E:\hello.txt", "r", encoding="UTF-8") as file:
content = file.read()
print(content)
这些模式可以组合使用,例如 ‘rb’ 表示以二进制模式读取文件,‘w+’ 表示以读写模式打开文件。
with open("E:\hello.txt", "r", encoding="UTF-8") as file:
for i in range(3):
print(file.readline())

with open("E:\hello.txt", "r", encoding="UTF-8") as file:
text=file.readlines()
print(text)
['hello world\n', 'this is a file\n', 'for my study']
with open("E:\hello.txt", "r+", encoding="UTF-8") as f:
# for line in f:
# print(line) # 全部读一遍后,指针到达结尾
f.seek(0,2) # 或者可以将指针移到末尾f.seek(偏移字节数,位置(0:开始;1:当前位置;2:结尾))
text = ["第四行,\n", "第五行\n"]
f.writelines(text)
with open("E:\hello.txt", "w+", encoding="UTF-8") as f:
text = ["新的第一行\n", "新的第二行\n"] # 清空原内容
f.writelines(text) # 写入新内容,指针在最后
f.seek(0,0) # 指针移到开始
print(f.read()) # 读取内容
with open("E:\hello.txt", "a+", encoding="UTF-8") as f:
text = ["新的第三行\n", "新的第四行\n"]
f.writelines(text) # 指针在最后,追加新内容,
f.seek(0,0) # 指针移到开始
print(f.read()) # 读取内容
ls = []
d = {"name": "mybaby"}
try:
y = m
except Exception as e: # 虽不能获得错误具体类型,但可以获得错误的值
print(e)