13.python的文件操作

#-*-coding:UTF-8-*-
#python文件操作
#字符对象操作
import locale
print locale.getpreferredencoding()           #得到系统默认的编码信息
with open('C:\Users\Administrator\Desktop\工作计划.txt'.decode('utf-8'),'r') as f:
    print  f.read().decode('cp936')  #对读取的字符串进行解码,解码用的格式可以从操作系统得到
#在windows中,如果读取的文档中包含中文,可以用gb2312编码格式来读取
print locale.getpreferredencoding()             #获得默认编码信息
print a_file.encoding
print a_file.mode
print a_file.name

a_file.seek(0)                          #将指针移到文件头
print a_file.read(6)                    #读取字符个数

a_file.close()                          #关闭,但是a_file依然存在
print  a_file.closed

#流对象有一个显式的close()方法,但是如果代码有缺陷,在调用close()方法前就崩溃了,那么这个文件将在相当长的一段时间内一直是打开的。
#解决办法,使用with语句
with open('C:/Users/Administrator/Desktop/a.txt') as a_file:
    a_file.seek(6)
    a_char=a_file.read(3)
    print type(a_char)
    print(a_char)                  #当代码段结束,程序自动调用a_file。close(),无论我们以何种方式跳出with语句,python会自动关闭那个文件,从技术上来说with语句创建了一个运行时环境
    print a_file.readline()

#写入文件
#两种模式
#1.“写”模式,传递mode='w'参数给open()函数
#2.“追加”模式会在文件末尾添加数据。传递mode='a'参数给open()函数
#两种模式都会自动创建新文件
with open('C:/Users/Administrator/Desktop/a.txt',mode='a') as a_file:
    a_file.write('test a test')


#二进制文件的读取
with open('C:/Users/Administrator/Desktop/a.jpg',mode='rb') as an_image:
    print an_image.mode
    print an_image.encoding
    print type(an_image)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值