• 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)
    

  • 相关阅读:
    体验一下:AndroidX
    Android研发技术的进阶之路
    App 冷启动与热启动及启动白屏优化
    Android Q 正式命名为 Android 10
    Android开发学习路线的七个阶段和步骤
    安卓旅途之——开发数独(一)
    项目总结
    小组互评与自评
    典型用户与场景
    第二个Sprint计划
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145130.html
Copyright © 2020-2023  润新知