python 基础教程之7 文件操作,文件写入,None

linux python基础教程 python 3.5

Posted by ivo on March 20, 2018

0x14 文件读操作

  • python可以非常简单的处理文件,文件在被编辑或读取之前需要先open
  • open参数里面写的是文件的path 如果文件和程序是同级目录,直接写文件名即可
    myfile = open("filename.txt")
    
  • 打开文件时候添加第二个参数可以改变文件打开的方式
    • r 只读
    • w 写入
    • a 追加
    • b 以二进制方式打开
      # write mode
      myfile = open("filename.txt","w")
      
      # read mode
      myfile = open("filename.txt","r")
      
      myfile = open("filename.txt")
      # binary write mode
      myfile = open("filename.txt","wb")
      
  • 文件打开后必须要close
    file = open("filename.txt","w")
    # do something
    file.close()
    
  • 文档类型的文件能够用read模式打开
    file = open("filename.txt","w")
    count = file.read()
    print(count)
    file.close()
    
  • 给read加参数,读取指定长度
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> for i in range(5):
    ...     print(file.read(8))
    ...
    “Neurons
     are the
     informa
    tion-pro
    cessing
    
    >>> for i in range(5):
    ...     print(file.read(3))
    ...
    uni
    ts
    in
    the
     br
    
    >>> for i in range(5):
    ...     print(file.read(20))
    ...
    ain, and the cerebra
    l cortex is the part
     of the brain that c
    an combine informati
    on from different so
    
  • 文件前部分被加参数的读取过没close时候,不加参数读取剩余部分
    >>> print(file.read())
    urces and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
    
  • 什么都不加只读取一次那么是读取文件整体的。
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> print(file.read())
    “Neurons are the information-processing units in the brain, and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
    
  • 读完一次再读,那么会返回一个空的string
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> print(file.read())
    “Neurons are the information-processing units in the brain, and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
    >>> print(file.read())
    
  • 获取文件中的字符长度
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> str = file.read()
    >>> print(len(str))
    429
    
  • 以行为单位处理文件,readlines()方法
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> print(file.readlines())
    ['"Neurons are the information-processing units in the brain, \n', 'and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, \n', 'recognize patterns,\n', ' make decisions to act differently based on past experience and start making predictions for the future,\n', '" Suzana Herculano-Houzel, \n', 'the Vanderbilt professor who developed the method for measuring neurons, \n', 'told ABC News.\n']
    
  • 用for 循环来实现文件的单行处理
    >>> file = open("/home/ivo/test/python_phone/book","r")
    >>> for line in file:
    ...     print(line)
    ...
    "Neurons are the information-processing units in the brain,
    and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations,
    recognize patterns,
     make decisions to act differently based on past experience and start making predictions for the future,
    " Suzana Herculano-Houzel,
    the Vanderbilt professor who developed the method for measuring neurons,
    told ABC News.
    >>>
    
  • 输出行的时候是用空格来进行分割的,最后自动添加的换行符

0x15 文件写操作

  • 文件写入,写入时候是新文件,所以文件不存在没关系,不会报错
    >>> file = open("/home/ivo/test/python_phone/word","w")
    >>> file.write("This has been written to a file")
    31
    >>> file.close()
    >>> file = open("/home/ivo/test/python_phone/word","r")
    >>> print(file.read())
    This has been written to a file
    >>> file.close()
    
  • 文件写入的时候之前的内容会被覆盖
    >>> file = open("/home/ivo/test/python_phone/word","r")
    >>> print(file.read())
    This has been written to a file
    >>> file.close()
    
    >>> file = open("/home/ivo/test/python_phone/word","w")
    >>> file.write("Some new text")
    13
    >>> file.close()
    
    >>> file = open("/home/ivo/test/python_phone/word","r")
    >>> print(file.read())
    Some new text
    >>> file.close()
    
  • 文件一旦被w模式打开里面的内容就会被删除
    >>> file = open("/home/ivo/test/python_phone/word","r")
    >>> print(file.read())
    Some new text
    >>> file.close()
    >>> file = open("/home/ivo/test/python_phone/word","w")
    >>> file.close()
    >>> file = open("/home/ivo/test/python_phone/word","r")
    >>> print(file.read())
    
  • write模式下返回的字符是写操作成功的标志指的是写入了多少字符或者可以表示为file.write(msg) == len(msg)
    >>> msg = "Hello world"
    >>> file = open("/home/ivo/test/python_phone/word","w")
    >>> amount_written = file.write(msg)
    >>> print(amount_written)
    11
    >>> file.close()
    
  • 为避免资源浪费在操作文件后确认它关闭是一个好的习惯。可以用try finally来实现
    >>> file = open("/home/ivo/test/python_phone/word","w")
    >>> file.write("good is good")
    12
    >>> file.close()
    
    >>> try:
    ...     file = open("/home/ivo/test/python_phone/word","r")
    ...     print(file.read())
    ... finally:
    ...     file.close()
    ...
    good is good
    
  • 即使中间出错了 try也会close
  • with as方式打开文件
    >>> with open("/home/ivo/test/python_phone/word") as f:
    ...     print(f.read())
    ...
    good is good
    
  • 使用with是自动close的,with结束,close结束。即使中间发生错误

    0x16 None

  • None是用来表示缺少的值,类似于其他与引种的null。像其他的空值,比如 0, [],空字符串转换成布尔值都是False。在python里面输入,它显示为空字符串
    >>> None == None
    True
    
    >>> None
    
    >>> print(None)
    None
    
  • None对象在函数中用于返回任何不明确的意义
    >>> def some_fun():
    ...     print("Hi!")
    ...
    >>> var = some_fun()
    Hi!
    >>> print(var)
    None
    
    >>> foo = print()
    
    >>> if foo == None:
    ...     print(1)
    ... else:
    ...     print(2)
    ...
    1