• python中的对文件的读写


    简单的实例

    open函数获取文件,w是写权限,可以对文件进行io操作

    file=open('C:/Users/Administrator/Desktop/yes.txt','w')
    file.write('Hello world')

    进一步,创建文件,写入文本

    初级难度:定义方法,输入文本名称,和文本内容,方法可以据此创建对应的文件,写入对于的文本;

    #encoding:utf-8
    def createFile(fileName,content):
        filePath="C:/Users/Administrator/Desktop/"
        fullPath=filePath+fileName+'.txt'
        file=open(fullPath,'w')
        file.write(content)
        file.close()
        print ("操作完成!")
    #尝试调用
    createFile("1","创建一个文件")

    创建一个文本替换的方法

    将指定的文本进行替换 返回

    #   文本替换的方法
    def textFilter(content,sourceWord,trgtWord):
        return content.replace(sourceWord,trgtWord)

    最后将两个方法进行组合

    对于输入的文本进行替换后,保存到制定的文本中

    #encoding:utf-8
    
    #   文本替换的方法
    def textFilter(content,sourceWord,trgtWord):
        return content.replace(sourceWord,trgtWord)
    
    # 定义文本的创建
    def createFile(fileName,content):
        filePath="C:/Users/Administrator/Desktop/"
        fullPath=filePath+fileName+'.txt'
        file=open(fullPath,'w')
        content=textFilter(content,'好','坏')
        file.write(content)
        file.close()
        print ("操作完成!")
    #尝试调用
    createFile("123","今天天气真好")
  • 相关阅读:
    linux下php调试工具xdebug安装配置
    linux下php开发环境搭建(nginx+php+mysql)
    centos7使用docker部署gitlab-ce-zh应用
    CentOS7上Docker安装与卸载
    struts2 中 paramsPrepareParamsStack 拦截器
    ModelDriven & Preparable 接口
    OLW Test
    sqlserver 错误:2,错误40
    C#时间截
    http post发送
  • 原文地址:https://www.cnblogs.com/inyu/p/13659098.html
Copyright © 2020-2023  润新知