zoukankan      html  css  js  c++  java
  • Python 学习开发笔记之IO操作

    文件或者目录的路径操作

    1. 获取当前工作目录

      import os
      import sys
      cwd = os.getcwd()
      
    2. 路径的拼接

      os.path.join(path,"dir")
      os.path.normpath(path + "/" + "dir")
      
    3. 路径的跨平台标准化

      os.path.normsize(path)
      
    4. 求取父路径

      path.split("/")[0]
      
    5. 判断是否是目录

      if os.path.isdir(path):
      
    6. 判读是否是文件

      if not os.path.isfile(path):
      
    7. 判断文件或者路径是否存在

      if os.path.exists(path):
      

    Python文件操作

    1. 新建文件

      with open(path,'w') as file:
          file.write(stringContent)
      
    2. 删除文件

      if os.path.isfile(path):
          os.remove(path)
      else:
          print(path," is not a file")
      
    3. 文件的读取

      with open(path) as file:
          content = file.readline()
          if len(content) == 0:
              print("EOF")
      
    4. 文件的写入

      with open(path,'w') as file:
          file.write(contentString)
      
    5. 移动文件

      import shutil
      shutil.copyfile(src,des)
      
    6. 重命名文件

      os.rename(path) #error when path is directory
      

    Python目录操作

    1. 子目录显示

      os.listdir(path)
      
    2. 目录的遍历

      # deep order first traversal
      import os
      def traversal(path):
          if not os.path.isdir(path):
              dosomething()
          else:
              for l in os.listdir(path):
                  traversal(os.path.join(path,l))
      
      
    3. 新建目录

      import os
      os.mkdir(path)
      os.makedirs(path)
      
    4. 删除目录

      import shutil
      shutil.rmtree(path) 
      os.removedirs(path)
      os.rmdir(path) # when path is empty directory
      
    5. 重命名目录

      import os
      os.renames(path1,path2)
      
    6. 移动目录

      import shutil
      shutil.copy(src,des)
      
      
  • 相关阅读:
    nyoj_518_取球游戏_201404161738
    nyoj_528_找球号(三)_201404152050
    nyoj_68_三点顺序_201404152013
    nyoj_123_士兵杀敌(四)_201404131143
    树状数组
    nyoj_116_士兵杀敌(二)_201404131107
    hdu_1024_糖果大战_201404021640
    hdu_1205_吃糖果_201404021440
    nyoj_278_排队_201403282135
    nyoj_127_星际之门(一)_201403282033
  • 原文地址:https://www.cnblogs.com/peaceWang/p/Python-xue-xi-kai-fa-bi-ji-zhiIO-cao-zuo.html
Copyright © 2011-2022 走看看