• Python基础-文件操作


    获取文件句柄:file = open(filepath,mode,encoding) 以mode模式,和coding的编码方式打开filepath路径下的文件(其中mode可以是r,w,a,读写r+(常用),写读w+(以w+方式打开文件和w方式打开文件一样都会覆盖原来文件内容,所以不常用),追加读a+;rb,wb,ab)
     
    读取内容:read() 读取文件中全部内容 注:read可以添加参数,用于指定读取的数量    readline() 读取文件中一行内容
     
    写入内容:write("content") 向文件中写入内容
     
    关闭文件句柄:close()
     
    获取文件光标的位置:tell()
     
    移动光标:seek(index) 将文件光标移动到Index位置
     
    清空缓存区:flush() 将缓存区中的数据写到文件中
     
    截断文本:truncate(start) 从start位置开始截断(删除)文章内容
     
    with语句:
    with open('log1') as obj1,open('log2') as obj2:
        文件操作
    通过with语句操作文件python解释器会在with语句结束后自动关闭文件
    注:
    1. 以二进制向文件中写入字符串需要将字符串进行编码比如str.encode("utf-8")
    2. 使用for循环文件,每次循环将读取文件中的一行
     
  • 相关阅读:
    LeetCode 023 Merge k Sorted Lists
    LeetCode 022 Generate Parentheses
    LeetCode 020 Valid Parentheses
    LeetCode 019 Remove Nth Node From End of List
    LeetCode 018 4Sum
    LeetCode 017 Letter Combinations of a Phone Number
    Linux常用命令详解(3)
    Linux常用命令详解(2)
    Linux常用命令详解(1)
    部署cobbler服务器
  • 原文地址:https://www.cnblogs.com/chiang97912/p/7233477.html
Copyright © 2020-2023  润新知