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)
    

  • 相关阅读:
    插入排序
    选择排序
    P1338 末日的传说 逆序数对
    P1582倒水 位运算
    P2158 [SDOI2008] (欧拉函数
    HDU 6274 二分+预处理(CCPC K题
    P1219 N皇后
    [USACO1.5] 回文质数
    Codeforces #123D: 后缀数组+单调栈
    单调栈 单调队列
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145130.html
Copyright © 2011-2022 走看看