读写文件


 

如何使用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 首先导入模块)

 

posted @ 2016-12-14 19:50  回冬  阅读(182)  评论(0编辑  收藏  举报