(08)文件与目录

==================================
修订时间:
17:36 2016-03-03 星期四
14:22 2015-2-2 星期一
==================================
文件头通用写法
#!/usr/bin/python
#conding:utf8

■ 文件一些操作
  fo=open('/root/test.txt')    # 打开一个文件    也可以用 file    fo=file("/root/test.txt")  默认是只读模式
  fo.read()  # 读一个文件
  fo.readline() # 一行一行往下读 大文件操作
  fo.readlines() # 一行一行读,一次读到内存中,用一个列表保存,每一个行是一个列表元素
  fo.close()  #关闭一个文件
  fo.mode #显示文件打开的模式
  fo.closed #检测文件是否关闭
-----------------
   r   只读
   r+ 读写
   w  写入  先删除原文件 ,再重新写入,如果文件没有则创建
   w+ 读写 先删除原文件 ,再重新写入,如果文件没有则创建  (可写入输出)

   a  写入  在文件 末尾追加新的内容,文件不存在,则创建
   a+ 读写 在文件 末尾追加新的内容,文件不存在,则创建
   b 打开二进制的文件
   U 支持所有的换行符

   写:
     fnew= open('/root/new.txt','w')   #fnew= open('/root/new.txt','r+)  
     fnew.write('hello   I am new')写到文件最后
     fenw.close()
   注意隐形指针, 最开始指第一个字母,读写都会移动指针
     可以看写的效果
      fnew= open('/root/new.txt','r')
      for line in fnew.readlines():
      print line

■ 文件对象方法:
   close()  readline([size])  readlines([size])  read([size])  next()  write(string)  writelines(List)
   seek() flush()

    for i in open('test.txt'): #  会打印每一行
          print i
  
■ OS 模块
    import  os
    os.mkdir("test")
  ●相关方法  mkdir() makedirs()  rmdir() removedirs() listdir()
              getcwd() chdir() walk()

  ●目录遍历
    ◆ 递归函数
       import os
       def dirList(path)
             filelist=os.listdir(path)
             allfile = []
             for filename in filelist
      filepath=os.path.join(path,filename)
      if os.path.isdir(filepath)
            dirList(filepath)
      allfile.append(filepath)
             return allfile
            
       allfile=dirList('root/testdir')
       print allfile
            

    ◆ 内置函数
      OS.walk()
    import os
    for path,d,fileList os.walk('/root/testdir'):
         for filename in fileList:
                          os.path.join(path,filename)
                         
    # 文件的绝对路径
    >>> import os.path
    >>> os.path.abspath("225.py")
   
    # 分开目录和文件
    >>> os.path.split("/home/www/tests.py")
   
    # 判断
    >>> os.path.exists("/home/www/")
    os.path.isabs(path)
    os.path.isdir(path)
   
    # 组合路径
    >>> os.path.join("/home/python","/BasicsPython","226.md"

原文地址:https://www.cnblogs.com/toby2chen/p/5197390.html