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 首先导入模块)

  • 相关阅读:
    pandas 读取excle ,迭代
    prettytable模块(格式化打印内容)
    Python开发丨这些面试题会不会难倒你
    python开发最受欢迎的十款工具
    语言组成
    运算符优先级
    Python 位运算符 逻辑运算符 成员运算符
    **算术运算符
    **Python数据类型转换
    字符串-数字-列表(转换)
  • 原文地址:https://www.cnblogs.com/llw1121/p/6180668.html
Copyright © 2011-2022 走看看