zoukankan      html  css  js  c++  java
  • Python文件操作,open读写文件,追加文本内容(转)

     1 1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
     2 file_object = open('thefile.txt')
     3 try:
     4  all_the_text = file_object.read( )
     5 finally:
     6  file_object.close( )
     7 注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
     8 2.读文件读文本文件input = open('data', 'r')
     9 #第二个参数默认为r
    10 input = open('data')
    11 
    12 读二进制文件input = open('data', 'rb')
    13 读取所有内容file_object = open('thefile.txt')
    14 try:
    15  all_the_text = file_object.read( )
    16 finally:
    17  file_object.close( )
    18 读固定字节file_object = open('abinfile', 'rb')
    19 try:
    20  while True:
    21  chunk = file_object.read(100)
    22  if not chunk:
    23  break
    24  do_something_with(chunk)
    25 finally:
    26  file_object.close( )
    27 读每行list_of_all_the_lines = file_object.readlines( )
    28 如果文件是文本文件,还可以直接遍历文件对象获取每行:
    29 for line in file_object:
    30  process line
    31 3.写文件写文本文件output = open('data.txt', 'w')
    32 写二进制文件output = open('data.txt', 'wb')
    33 追加写文件output = open('data.txt', 'a')
    34 
    35 output .write("
    都有是好人")
    36 
    37 output .close( )
    38 
    39 写数据file_object = open('thefile.txt', 'w')
    40 file_object.write(all_the_text)
    41 file_object.close( )
  • 相关阅读:
    8.存储器
    7.计算机的总线
    6.计算机的字符与编码集
    5.计算机的计量单位
    JAVA 实用插件
    并发(三)
    并发(二)
    Java 8 Lambda
    并发(一)
    Mybatis(七)-- LRU LFU 算法
  • 原文地址:https://www.cnblogs.com/kennyhr/p/3527060.html
Copyright © 2011-2022 走看看