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

    Python读写文件

    工作目录

    import os
    print(os.getcwd())#获取当前工作目录,
    #C:Users10365PycharmProjectsuntitled
    os.chdir('C:\Windows\System32')#改变工作目录
    

    创建文件夹

    import os
    os.makedirs('C:\delicious\walnut\waffles')#路径中没有的文件夹也会被创建
    

    处理绝对路径和相对路径

    os.path.abspath(path)#将指定的相对路径转换为绝对路径
    os.path.isabs(path)#如果path是绝对路径就返回True,是相对路径就返回False
    os.path.relpath(path,start)#返回从start到path的相对路径
    os.path.dirname(path)#返回除文件名之外的目录路径名称
    os.path.basename(path)#只返回文件名
    os.path.split(path)#返回元组,元组包含分离出的目录路径和文件名
    os.path.join(path,filename)#将path和文件名连接起来
    

    查看文件大小和文文件夹内容

    os.path.getsize(path)#查看path路径中文件的字节数
    os.listdir(path)#返回文件名字符串列表
    

    检查路径的有效性

    os.path.exists(path)#判断path路径是否存在,返回布尔值
    os.path.isfile(path)#判断path是否是一个文件,返回布尔值
    os.path.isdir(path)#判断path是否是一个目录,返回布尔值
    

    操作文件

    #python打开指定路径的文件,不能是目录,返回一个file对象,然后通过file对象可以对文件进行相应的读写操作,第二个参数可以指定覆盖还是添加
    file = open(path,'w')#覆盖模式
    file = open(path,'a')#添加模式
    content = file.read()#对文件进行读操作
    contentlist = file.readlines()#返回一个字符串列表
    length = file.write(str)#对文件写入字符串
    file.close()#释放资源
    

    shelve模块保存变量

    #shelve是python中用来持久化存储的字典模块
    import shelve, os
    os.chdir('C:\Users\10365\Desktop')
    shelfFile = shelve.open('mydata')
    cats = ['Zpphie', 'Pooka', 'Simon']
    shelfFile['cats'] = cats#保存值
    print(shelfFile['cats'])#通过传入key值来获取value
    shelfFile.close()#关闭资源
    

    pprint.pformat()函数保存变量

    import pprint,os
    os.chdir('C:\Users\10365\Desktop')
    cats = [{'name':'Zophie','desc':'chubby'},{'name':'pooka','desc':'fluffy'}]
    fileObj = open('myCats.py','w')
    fileObj.write('cats = ' + pprint.pformat(cats) + '
    ')#以cats = [{'name':'Zophie','desc':'chubby'},{'name':'pooka','desc':'fluffy'}]的形式保存到文件中
    fileObj.close()
    
    #直接使用myCats.py
    import myCats
    print(myCats.cats)
    

    参考《python编程快速上手——让繁琐的工作自动化》

  • 相关阅读:
    直线的中点Bresenham算法的实现
    使用git 将自己的本地文件git到github上面的完整过程
    利用Microsoft VC++6.0 的MFC 的绘图工具实现简单图形的绘制
    github常见操作和常见错误及其解决办法
    浅谈软件配置管理工具(github & SVN)
    为Github 托管项目的访问添加SSH keys
    jQuery:用 lightTreeview 实现树形分类菜单的功能 展开收缩分类代码
    程序设计7大面向对象设计原则
    计算机组成原理实验之模拟整机实验考核试题
    计算机组成原理实验之CPU组成与指令周期实验
  • 原文地址:https://www.cnblogs.com/JAVA-54188/p/13775585.html
Copyright © 2011-2022 走看看