zoukankan      html  css  js  c++  java
  • python文件相关

    文件操作基本流程初探

    f = open('chenli.txt') #打开文件
    first_line = f.readline()
    print('first line:',first_line) #读一行
    print('我是分隔线'.center(50,'-'))
    data = f.read()# 读取剩下的所有内容,文件大时不要用
    print(data) #打印读取内容
     
    f.close() #关闭文件

    打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

    打开文件的模式有:

    • r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    • w,只写模式【不可读;不存在则创建;存在则清空内容】
    • x, 只写模式【不可读;不存在则创建,存在则报错】
    • a, 追加模式【可读;   不存在则创建;存在则只追加内容】

    "+" 表示可以同时读写某个文件

    • r+, 读写【可读,可写】
    • w+,写读【可读,可写】
    • x+ ,写读【可读,可写】
    • a+, 写读【可读,可写】

     "b"表示以字节的方式操作

    • rb  或 r+b
    • wb 或 w+b
    • xb 或 w+b
    • ab 或 a+b

     注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

    上下文管理,优化打开方式

    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)

    文件的修改

    import os
    with open('a.txt','r',encoding='utf-8') as read_f,
            open('.a.txt.swap','w',encoding='utf-8') as write_f:
        for line in read_f:
            if line.startswith('hello'):
                line='哈哈哈
    '
            write_f.write(line)
    
    os.remove('a.txt')
    os.rename('.a.txt.swap','a.txt')
  • 相关阅读:
    通过TortoiseGit上传项目到GitHub
    删除右键菜单中的Git Gui Here、Git Bash Here的方法
    block functions区块函数插件的定义与使用
    modifiers标量调节器插件的定义和使用
    functions函数插件的定义和使用
    smarty内置函数、自定义函数
    smarty类与对象的赋值与使用
    Smarty模板的引用
    Smarty的循环
    Smarty的条件判断语句
  • 原文地址:https://www.cnblogs.com/pythonclass/p/7230500.html
Copyright © 2011-2022 走看看