• Python3-文件操作


    一、open()-----read()
     1 stream = open(r"F:FileOperationlyrics.txt")
     2 container = stream.read()
     3 print(container)
     4  
     5 print("-"*30)
     6  
     7 stream = open(r"F:FileOperationlyrics.txt") # 默认r
     8 containerable = stream.readable() # 判断是否可读
     9 if containerable:
    10     while True:
    11         container = stream.readline() # 读取一行
    12         print(container)
    13         if not container:
    14             break
    15  
    16 print("-"*30)
    17  
    18 stream = open(r"F:FileOperationlyrics.txt")
    19 container = stream.readlines() # 读取多行
    20 for i in container:
    21     print(i)
    22  
    23  
    24 stream = open(r"F:FileOperationdemoDaoJi.jpg",'rb') # 图片mode应为'rb'
    25 containerable = stream.readable()
    26 if containerable:
    27     container = stream.read()
    28     print(container)

     

     
    二、open()----write()
     1 stream = open(r"F:FileOperationmagic.txt",'w') 
     2 # magic.txt原内容:Sweetmagic
     3 containerable = stream.writable() # 判断是否可写
     4 if containerable:
     5     container = stream.write("Hello World") 
     6     # write()每次都会将原来的内容清空,然后写入当前的内容
     7     stream.close() # 此时内容:Hello World
     8     # container = stream.write("Hello kitty")
     9     # ValueError: I/O operation on closed file.
    10     # 每次只要经过close()操作,无法再写入
    11  
    12 stream = open(r"F:FileOperationmagic.txt",'w') # 原内容:Hello World
    13 stream.writelines(["Sweet Magic
    ","Sakura
    ","Seele
    "]) # writelines()并没有换行效果,需要手动加"
    "
    14 stream.close()
    15 """
    16 此时内容:
    17 Sweet Magic
    18 Sakura
    19 Seele
    20 """
    21  
    22 stream = open(r"F:FileOperationsweet.txt",'a') 
    23 # sweet.txt原内容:Hello World ,'a'-->append,追加,在原内容后面追加新内容
    24 stream.write("Sweet Magic")
    25 stream.close() # 此时内容:Hello WorldSweet Magic

     

     
    三、复制
    with open(r"F:FileOperationp1demoDaoJi.jpg",'rb') as stream:
        container = stream.read()
        with open(r"F:FileOperationp2demoDaoJi.jpg",'wb') as wstream:
            wstream.write(container)
    print("文件复制完成!")
     
  • 相关阅读:
    php checkbox 复选框
    wp7 The remote connection to the device has been lost
    php json_decode null
    今入住博客园,希望笑傲职场!
    单例模式之见解设计模式
    简单工厂之见解设计模式
    infopath 序列化 在发布处有导出源文件.存放一地方后有myschema.xsd 文件
    超简单的天气预报webpart
    用户控件传值
    Proxy代理
  • 原文地址:https://www.cnblogs.com/DemonKnifeGirl/p/12997284.html
Copyright © 2020-2023  润新知