分享

python对文件 文件夹的操作

 心不留意外尘 2016-08-04

http://elan1986./blog/1123579

2011
  1. #-*-coding: UTF-8 -*-  
  2.   
  3. import os  
  4.   
  5.   
  6. s = os.getcwd()#获取当前目录  
  7. print s  
  8.   
  9. os.chdir("E:\\PyWk\\nodepad_py") #更改当前目录  
  10.   
  11. fpath, fname = os.path.split("E:\\PyWk\\nodepad_py\\09.py") #将一个路径分解为目录名和文件名  
  12. print fpath, fname  
  13.   
  14. fpathandname, fext = os.path.splitext("E:\\PyWk\\nodepad_py\\09.py") #分解文件名的扩展名  
  15. print fpathandname, fext  
  16.   
  17. a = os.path.exists("E:\\PyWk\\nodepad_py\\erro.py") #判断文件或目录是否存在  
  18. print a  
  19.   
  20. b = os.path.isfile("E:\\PyWk\\nodepad_py\\09.py") #判断是否文件  
  21. print b  
  22.   
  23. c = os.path.isdir("E:\\PyWk\\nodepad_py\\09.py") #判断是否是目录  
  24. print c  
  25.   
  26. list = os.listdir("E:\\PyWk\\nodepad_py") #获取目录下的文件以及子目录列表  
  27. print list  
  28.   
  29. #os.makedirs("c:\\test1\\test2\\test3") #创建子目录  
  30.   
  31. #f = open("c:\\test1\\test2\\test3\\test4.txt", 'w') #创建一个空文件  
  32. #f.close()  
  33.   
  34. #os.rmdir("c:\\test1\\test2\\test3") #删除子目录  
  35.   
  36. #os.remove("c:\\test1\\test2\\test3\\test4.txt") #删除文件  
  37.   
  38.   
  39. os.chdir('c:\\test1\\test2\\test3')  
  40. print os.getcwd()  
  41. list = os.listdir(os.getcwd())  
  42. print list  
  43. os.rename("test4.txt", "newtest4.txt")  


Python代码  收藏代码
  1. #-*-coding: UTF-8 -*-  
  2. #显示某一目录下所有文件夹  
  3. import os  
  4. def getDirList(p):  
  5.     p = str(p)  
  6.     if p == '':  
  7.         return []  
  8.     p = p.replace('\\', '\\\\')  
  9.     if p[-1] != "\\":  
  10.         p = p+"\\"  
  11.     a = os.listdir(p)  
  12.     b = [x for x in a if os.path.isdir(p+x)]  
  13.     return b  
  14. print getDirList("c:\\")  



Python代码  收藏代码
  1. #-*-coding: UTF-8 -*-  
  2. #获取某目录下所有文件列表  
  3. import os  
  4. def getFileList(p):  
  5.     p = str(p)  
  6.     if p == "":  
  7.         return []  
  8.     p = p.replace('\\', '\\\\')  
  9.     if p[-1] != '\\':  
  10.         p = p + '\\'  
  11.     a = os.listdir(p)  
  12.     b = [x for x in a if os.path.isfile(p+x)]  
  13.     return b  
  14.   
  15. print getFileList("c:\\")  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多