zoukankan      html  css  js  c++  java
  • 读写文件


    如何使用Python在硬盘上创建,读取,保存文件


     import os 处理文件,文件夹,文件路径

     import shelve 保存变量(保存 Python 程序中的数据)


    一、文件与文件路径

     os.path 模块    

                  os.path.join() 返回文件路径字符串

                  os.path.abspath() 返回绝对路径字符串

                  os.path.isabs() 是否为绝对路径

                  os.path.relpath(path, start) 返回从start开始到path的相对路径

                  os.path.dirname() 返回最后一个斜杠之前所有内容

                  os.path.basename() 返回最后一个斜杠之后所有内容

                  os.path.split() 返回一个列表,包括路径所有部分

                  os.path.exists() 文件或文件夹是否存在

                  os.path.isfile() 参数存在,并且是一个文件

                  os.path.isdir() 参数存在,并且是一个文件夹

                  os.path.getsize() 返回文件字节数

     os.listdir() 返回文件名字符串列表

     os.makedirs() 创建文件夹

     os.chdir() 取得当前工作路径字符串

     os.getcwd() 改变当前工作路径字符串

    二、文件读写过程

    步骤:

    (1)调用 open() 函数,返回一个 File 对象。

    (2)调用 File 对象的 read() 或 write () 方法。(读取,写入)

    (3)调用 File 对象的 close() 方法,关闭该文件。

    三、写入文件

    open('bacon.txt', 'w')   #新建
    open('bacon.txt', 'a')   #添加
    

      

    四、保存变量

     import shelve 保存变量(保存 Python 程序中的数据)

     pprint.pformat() 保存变量(import pprint 首先导入模块)

  • 相关阅读:
    ableview中,如何加载自定义cell? 如何改变选中某一行的颜色(或不显示颜色)
    NSRunLoop
    知识点
    类别、延展、继承
    换个地方,说点儿真话,谈点儿人生中的循环定理
    ios-UIViewController的生命周期
    ios-UIView的一些常用的方法
    ios-Frame和bounds的区别
    ios-AppDelegate常用的方法
    ios取沙盒(sandbox)中的路径
  • 原文地址:https://www.cnblogs.com/llw1121/p/6180668.html
Copyright © 2011-2022 走看看