zoukankan      html  css  js  c++  java
  • 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)
    

  • 相关阅读:
    Spring spEL
    Spring 使用外部部署文件
    Spring 自动装配
    spring 属性配置细节
    hdu 1054 Strategic Game
    fzu 2037 Maximum Value Problem
    将博客搬至CSDN
    HDU 4714 Tree2Cycle
    HDU 1009 The Shortest Path in Nya Graph
    POJ 1942 Paths on a Grid 组合数的优化
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145130.html
Copyright © 2011-2022 走看看