zoukankan      html  css  js  c++  java
  • Python数据类型文件

    文件也可以看作是Python中的数据类型。当使用Python的内置函数open打开一个文件时,返回一个文件对象。其原型如下所示:

      file=open(filename,mode,bufsize)                      

    • filename:要打开的文件名。
    • mode:可选参数,文件打开模式。 

            mode: 'r'表示以读方式打开文件,'w'表示以写方式打开文件,加入文件存在,则会覆盖源文件,'a'表示'以写方式打开文件,在原文件中添加内容,不会覆盖

            rb'表示以二进制读打开文件(读图片),'wb'表示以二进制写打开文件(写图片)

    • bufsize:可选参数,缓冲区大小。

    常用文件操作                                                                                                                                                  

    1.file.read()     将整个文件读入字符串中                                                                                                                                        

    #将整个文件一次性读入到内存中

    file=open('h:/test.txt','r')

    temp = file.read()               #temp的类型为字符串

    file.close()

    2.file.readline()   读取文件的一行到字符串中                                                                                                                                  

    #逐行读取文件

    file = open('h:/test.txt','r')

    temp = file.readline()

    while temp:

      print temp,

      temp=file.readline()

    file.close()

    #逐行读取文件的另一种方式(推荐)

    file = open('h:/test.txt','r')

    for line in file:

      print line

    file.close()

    3.file.readlines()     将整个文件读入到列表中                                                                                                                          

    4.file.write()       向文件中写入字符串                                                                                                                                  

    file=open('h:/test.txt','a')

    content="i write haha"

    file.write(content)

    file.close()

    5.file.writelines()     向文件中写入一个列表                                                                                                                          

    file=open('h:/test.txt','a')

    content=['tst1','tst2','\ntet']

    file.witelines(content)

    file.close()

    6.file.close()                                                                                                                                                                

  • 相关阅读:
    Building a flexiable renderer
    Indirect Illumination in mental ray
    我的心情
    Cellular Automata
    Subsurface Scattering in mental ray
    Shader Types in mental ray
    BSP Traversal
    我的渲染器终于达到了MR的速度
    How to handle displacement and motion blur
    说明
  • 原文地址:https://www.cnblogs.com/sallybin/p/3064597.html
Copyright © 2011-2022 走看看