#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/2 13:57
# @Author : 朱红喜
# @Site :
# @File : FileRead.py
# @Software: PyCharm
# open()有四个参数
# open(path,type,[encode],[ignoreError])
# 第一种读文件的方式 这里读取txt文件
try:
f1 = open("C:/users/breeziness/desktop/test.txt", 'r')
print(f1.read())
finally:
if f1:
f1.close()
# 第二种python自带的方式,with方式和前面的try ... finally是一样的,并且不必调用f.close()方法。
with open("C:/users/breeziness/desktop/test.txt", 'r') as f:
print(f.read())
# 这里读取二进制文件 图片 以‘rb’方式读取
with open("C:/users/breeziness/desktop/1.png", 'rb') as f:
print(f.read())
# 写文件 ‘w’方式直接覆盖原先内容 ‘a’append方式则是追加在后面
with open("C:/users/breeziness/desktop/test.txt", 'a') as f:
f.write('这是新写入的文本')
Python简单的文件读写
猜你喜欢
转载自blog.csdn.net/qq_40731414/article/details/82926057
今日推荐
周排行