zoukankan      html  css  js  c++  java
  • File operations 1

    1:只读(‘r' 和 ’rb'以字节读)

    f = open('d:模特主妇护士班主任.txt',mode='r',encoding='UTF-8')
     content = f.read()
     print(content)
     f.close()

    相对路径

     f = open('模特主妇护士班主任',mode='r',encoding='utf-8')
     content = f.read()
     f.close()
    
    若以rb模式,则不需encoding=.......

    2:读写('r+'和‘r+b'以bytes字节读写)

     f = open('log',mode='r+',encoding='utf-8')
     print(f.read())
     f.write('大猛,小孟')
     f.close()
    
    f = open('log',mode='r+b')
    print(f.read())
    f.write('大猛,小孟'.encode('utf-8'))
    f.close()

    3:只写('w'和'wb')

    先将源文件的内容全部清除,再写。

     f = open('log',mode='w',encoding='utf-8')
     f.write('附近看到类似纠纷')
     f.close()
    
     f = open('log',mode='wb')
     f.write('附近看到类似纠纷'.encode('utf-8'))
     f.close()

    4:写读

    w+ , w+b 

     f = open('log',mode='w+',encoding='utf-8')
     f.write('aaa')
     f.seek(0)
     print(f.read())
     f.close()

    5:追加 'a'

    f = open('log',mode='a',encoding='utf-8')
    f.write('佳琪')
    f.close()
    
    f = open('log',mode='ab')
    f.write('佳琪'.encode('utf-8'))
    f.close()
    
    注意:seek()--以字符定位光标位置,一个中文
    字体代表3个字符,一个英文字母代表一个字符

    6:文件操作其他功能

    # obj = open('log',mode='r+',encoding='utf-8')
    # content = f.read(3)  # 读出来的都是字符
    # f.seek(3)  # 是按照字节定光标的位置
    # f.tell() 告诉你光标的位置
    # print(f.tell())
    # content = f.read()
    # print(content)
    # f.tell()
    # f.readable()  # 是否刻度
    # line = f.readline()  # 一行一行的读
    # line = f.readlines()  # 每一行当成列表中的一个元素,添加到list中
    # f.truncate(4)
    # for line in f:
    #     print(line)
    # f.close()
    
    
    # f = open('log',mode='a+',encoding='utf-8')
    # f.write('佳琪')
    # count = f.tell()
    # f.seek(count-9)
    # print(f.read(2))
    # f.close()
    
    # with open('log',mode='r+',encoding='utf-8') as f,
    #         open('log',mode='w+',encoding='utf-8') as f1:

    作者:chauncylii

    出处:https://www.cnblogs.com/passengerlee/p/11965398.html

    版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。

    觉得文章不错,点个关注呗!

  • 相关阅读:
    leetcode 1. 两数之和
    leetcode 671. 二叉树中第二小的节点
    leetcode 100. 相同的树
    leetcode 110. 平衡二叉树
    leetcode 144. 二叉树的前序遍历
    1066. Root of AVL Tree (25)
    leetcode 100 相同的树
    leeCode 515 在每个树行中找最大值
    LeetCode 31.下一个排列
    面向对象UML中类关系
  • 原文地址:https://www.cnblogs.com/passengerlee/p/10351107.html
Copyright © 2011-2022 走看看