zoukankan      html  css  js  c++  java
  • 文件---Python

    ---恢复内容开始---

    读取文件:

    fin=open("test.txt")
    read=fin.readline()-----读一行
    for line in fin:
            print (line)
        fin.close()

    read=fin.read()----读取所有内容

    写入文件:

    fout=open('test.txt','w')----将文件中的原内容清空后写入
    line1='good afternoon'
    fout.write(line1)---write的参数必须是字符串
    fout.close()

    fout=open('test.txt','a')----在源文件后追加内容

    格式操作符---%:将表达式转化为字符串

     line='In  %d years I have spotted %g %s '%(3,0.1,'camels')

    文件名和路径:

    import os----OS莫阔提供了用于操作文件和目录的函数
    cwd=os.getcwd()----获取当前目录

     path=os.path.abspath('test.txt')----获取文件的绝对路径

    os.path.exists('test.txt')----检查文件或目录是否存在,返回布尔型

    os.path.isdir('test.txt')----检查是否为目录

    os.listdir(cwd)---返回指定目录中的文件列表

    os.path.isfile('test')---检查是否为文件

    os.path.join(dirname,name)----接受一个目录和文件名并拼成一个完整路径

    捕获异常:

    try:
        fin=open('test.txt')
        for line in fin:
            print (line)
        fin.close()
    except:
        print('something is wrong')

    编写模块:

    如果你有一个文件:example.py

    导入这个文件:import example

    使用example.py中的函数:example.linecount()

    os.path.

  • 相关阅读:
    C#中调用Outlook API 发起会议
    Log4Net配置
    web端调用Webapi获取Excel表格
    表格导出之Aspose.Cells
    验证输入框
    把新建的对象所有属性变成默认值
    省市区三级联动
    全局异常处理
    HttpHttpServletRequest / Reponse
    热部署
  • 原文地址:https://www.cnblogs.com/lwjl/p/4230312.html
Copyright © 2011-2022 走看看