代码
# -*- coding: utf-8 -*-
with open('E:/code/python_code/test.py') as file_object:
contents = file_object.read()
print(contents)
效果图
读写模式参数说明:
省略该参数, 只读模式
‘r’, 读取模式
‘w’, 写入模式(尤其注意,'w’模式会先查找并清空该文件内容,然后写入)
‘a’, 附加模式
‘r+’, 读取和写入模式
写完即读出会失败,明明有内容但是不能读出(其实原因是写操作后指针移动到了文件结尾位置,此时执行读操作不能读出刚写入的内容)
# -*- coding: utf-8 -*-
# with 方法可以在完成读写操作后自动close()文件
with open('E:/code/python_code/test.txt', 'a') as file_object:
file_object.write("hello, this is a python read and write test.\n")
contents = file_object.read()
print(contents)
完成写操作后再打开可以读出(因为这时读文件指针移动到了文件开始位置)
# -*- coding: utf-8 -*-
with open('E:/code/python_code/test.txt', 'a') as file_object:
file_object.write("hello, this is a python read and write test.\n")
# file_object.close()
with open('E:/code/python_code/test.txt', 'r') as file_object:
contents = file_object.read()
print(contents)