python之文件处理

  1. # -*- coding: utf-8 -*-  
  2.   
  3. import os  
  4. import shutil  
  5.   
  6. # 一. 路径操作:判断、获取和删除  
  7.   
  8. #1. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()  
  9. #print: currentpath:  f:\LearnPython  
  10. currentpath = os.getcwd()  
  11. print "currentpath: ",currentpath  
  12. #2. 返回指定目录下的所有文件和目录名:os.listdir()  
  13. #print:os.listdir():  ['test.txt', 'testRW.py', 'test1.txt', 'cmd.py', 'rwfile.py', 'downloadfile.py', 'date.py', 'time.py', 'datetime.py', 'file.py']  
  14. print "os.listdir(): ",os.listdir('f:\LearnPython')  
  15.   
  16. path = "F:\mmmmmmmmm\debug_taobao_200003@taobao_android1.6_3.2.1.apk"  
  17. #3. 判断给出的路径是否真地存:os.path.exists()  
  18. if os.path.exists(path):  
  19.     #删除一个文件:os.remove()  
  20.     os.remove(path)  
  21. else:  
  22.     print path,"not exist"  
  23.   
  24. #4. 删除多个目录:os.removedirs(“c:\python”)  
  25. #它只能删除空目录,如果目录里面有内容将不会被删除  
  26. if os.path.exists("d:/woqu"):  
  27.     os.removedirs("d:/woqu")  
  28. else:  
  29.     os.mkdir("d:/woqu")  
  30.     os.removedirs("d:/woqu")  
  31.   
  32. #5. 判断给出的路径是否是一个文件:os.path.isfile()  
  33. #print: True  
  34. print os.path.isfile("D:\hello\json.txt")  
  35. #6. 判断给出的路径是否是一个目录:os.path.isdir()  
  36. #print: True  
  37. print os.path.isdir("D:\hello")  
  38. #7. 判断是否是绝对路径:os.path.isabs()  
  39. #print: True  
  40. print os.path.isabs("D:\hello")  
  41. #  判断是否是链接  
  42. print os.path.islink('http://www.baidu.com')  
  43. #8. 返回一个路径的目录名和文件名:os.path.split()       
  44. #eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')   
  45. #print: ('D:\\hello', 'json.txt')  
  46. print os.path.split("D:\hello\json.txt")  
  47. #9. 分离扩展名:os.path.splitext()  
  48. #print:('D:\\hello\\json', '.txt')  
  49. print os.path.splitext("D:\hello\json.txt")  
  50. #10. 获取路径名:os.path.dirname()  
  51. #print: 'D:\\hello'  
  52. print os.path.dirname("D:\hello\json.txt")  
  53. #11. 获取文件名:os.path.basename()  
  54. #print: 'json.txt'  
  55. print os.path.basename("D:\hello\json.txt")  
  56.   
  57.   
  58. #13. 指示你正在使用的平台:os.name       对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'  
  59. print "os.name: ",os.name  
  60.   
  61. #14. linex 下的命令  
  62. if os.name == 'posix':  
  63.     #读取和设置环境变量:os.getenv() 与os.putenv()  
  64.     home_path = os.environ['HOME']  
  65.     home_path = os.getenv('HOME')  #读取环境变量   
  66. elif os.name == 'nt':  
  67.     home_path = 'd:'   
  68.     print 'home_path: ',home_path  
  69.   
  70. #15. 给出当前平台使用的行终止符:os.linesep    Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'  
  71. print(os.linesep)  
  72.   
  73. #16. 应为windows和linux的路径有点点不一样,windows是用 \\ 来分割的,linux是用 / 来分隔,  
  74. #而用os.sep 会自动根据系统选择用哪个分隔符。  
  75. print(os.sep)  
  76.   
  77. #17. 重命名:os.rename(old, new)  
  78. #先进入目录  
  79. os.chdir("d:\\hello")  
  80. print os.getcwd()   
  81. #18. 再重命名  
  82. os.rename("1.txt""11.txt")  
  83. #19. 创建多级目录:os.makedirs(“c:\python\test”)  
  84. os.makedirs('d:\h\e\l\l\o')  
  85. #20. 创建单个目录:os.mkdir(“test”)  
  86. os.mkdir('d:\f')  
  87. #21. 获取文件属性:os.stat(file)  
  88. #print: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=497L, st_atime=1346688000L, st_mtime=1346748054L, st_ctime=1346748052L)  
  89. print os.stat('d:\hello\json.txt')  
  90. #22. 修改文件权限与时间戳:os.chmod(path,mode)  
  91. #这里有介绍:http://blog.csdn.net/wirelessqa/article/details/7974477  
  92. #23. 终止当前进程:os.exit()  
  93. #24. 获取文件大小:os.path.getsize(filename)  
  94. print os.path.getsize('d:/hello/json.txt')  


文件操作:
os.mknod("test.txt")        创建空文件
fp = open("test.txt",w)     直接打开一个文件,如果文件不存在则创建文件

关于open 模式:

w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+     以读写模式打开
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb     以二进制读模式打开
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )

 

fp.read([size])                     #size为读取的长度,以byte为单位

fp.readline([size])                 #读一行,如果定义了size,有可能返回的只是一行的一部分

fp.readlines([size])                #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。

fp.write(str)                      #把str写到文件中,write()并不会在str后加上一个换行符

fp.writelines(seq)            #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

fp.close()                        #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。  如果一个文件在关闭后还对其进行操作会产生ValueError

fp.flush()                                      #把缓冲区的内容写入硬盘

fp.fileno()                                      #返回一个长整型的”文件标签“

fp.isatty()                                      #文件是否是一个终端设备文件(unix系统中的)

fp.tell()                                         #返回文件操作标记的当前位置,以文件的开头为原点

fp.next()                                       #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。

fp.seek(offset[,whence])              #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定 了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每 次进行写操作时,文件操作标记会自动返回到文件末尾。

fp.truncate([size])                       #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

 

目录操作:
os.mkdir("file")                   创建目录
复制文件:
shutil.copyfile("oldfile","newfile")       oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile")            oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir")        olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname")       文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")   
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir")    空目录、有内容的目录都可以删
转换目录
os.chdir("path")   换路径

实例:将文件夹下所有图片名称加上'_once-ler'

  1. # -*- coding:utf-8 -*-  
  2. import re  
  3. import os  
  4. import time  
  5. #str.split(string)分割字符串  
  6. #'连接符'.join(list) 将列表组成字符串  
  7.   
  8. def file_changename(filepath):     
  9.     global picnum        
  10.     file_path = os.path.split(filepath) #分割出目录与文件  
  11.     lists = file_path[1].split('.'#分割出文件与文件扩展名  
  12.     file_ext = lists[-1#取出后缀名(列表切片操作)  
  13.     img_ext = ['bmp','jpeg','gif','psd','png','jpg']  
  14.     if file_ext in img_ext:  
  15.         os.rename(filepath,file_path[0]+'/'+lists[0]+'_once-ler.'+file_ext)  
  16.         picnum+=1  
  17.   
  18.   
  19. def change_name(path):    
  20.     if not os.path.isdir(path) and not os.path.isfile(path):  
  21.         return False  
  22.     elif os.path.isfile(path):  
  23.         file_changename(path)  
  24.     elif os.path.isdir(path):  
  25.         for x in os.listdir(path):  
  26.             print 'os.path.join(path,x): ',os.path.join(path,x)  
  27.             file_changename(os.path.join(path,x))  
  28.             #os.path.join()在路径处理上很有用  
  29. if __name__ == '__main__':  
  30.     img_dir = 'D:\\hello\\capture'  
  31.     print img_dir  
  32.     img_dir = img_dir.replace('\\','/')  
  33.     print img_dir  
  34.     start = time.time()  
  35.     print start  
  36.     picnum = 0  
  37.     change_name(img_dir)  
  38.     spenttime = time.time() - start  
  39.     print('程序运行耗时:%0.2f'%(spenttime))  
  40.     print('总共处理了 %s 张图片'%(picnum))  

下面这个文件运行有错误,摘自: http://rsjy.org/2023.html
  1. #!/usr/bin/python  
  2. # -*- coding:utf-8 -*-  
  3. import os  
  4. # 定义几个函数  
  5. def del_file(wpath):  
  6.     os.remove(wpath)  # 删除文件  
  7. def del_dir(wpath):  
  8.     os.removedirs(wpath)  # 删除空文件夹  
  9. def gen_dir(wpath):  
  10.     if os.path.exists(wpath):  
  11.         pass  
  12.     else:  
  13.         os.mkdir(wpath)  # 建立文件夹  
  14. def gen_file(wpath):  
  15.     if os.path.exists(wpath):  
  16.         pass  
  17.     else:  
  18.         os.mknod(wpath)  # 建立文件  
  19.   
  20. print(os.sep)   
  21. print(os.linesep) # 字符串给出当前平台使用的行终止符  
  22.   
  23. # print(os.environ)  
  24. if os.name == 'posix':  
  25.     home_path = os.environ['HOME']  
  26.     home_path = os.getenv('HOME')  #读取环境变量    
  27. elif os.name == 'nt':  
  28.     home_path = 'd:'  # win 下未测试  
  29.   
  30. # 定义进行测试的文件夹与文件的名称  
  31. tep_dir = 'xx_tep'  
  32. tep_dir_a = 'tep_dir_a'  
  33. tep_dir_b = 'tep_dir_b'  
  34. tep_file_a = 'tep_file_a.txt'  
  35. tep_file_b = 'tep_file_b.py'  
  36. tep_file_c = 'tep_file_c.c'  
  37. # 合成文件夹与文件的全路径  
  38. path_tep = os.path.join(home_path, tep_dir)  
  39. path_dir_a = os.path.join(path_tep, tep_dir_a)  
  40. path_dir_b = os.path.join(path_tep, tep_dir_b)  
  41. path_file_a = os.path.join(path_dir_a, tep_file_a)  
  42. path_file_b = os.path.join(path_dir_a, tep_file_b)  
  43. path_file_c = os.path.join(path_dir_b, tep_file_c)  
  44. # 在系统内生成相应的文件夹与文件  
  45. gen_dir(path_tep)  
  46. gen_dir(path_dir_a)  
  47. gen_dir(path_dir_b)  
  48. gen_file(path_file_a)      
  49. gen_file(path_file_b)  
  50. gen_file(path_file_c)  
  51.   
  52. cwd = os.getcwd() # 得到当前工作目录,即当前Python脚本工作的目录路径。  
  53. wlist = os.listdir(cwd)  
  54. for wli in wlist:  
  55.     print(wli)  
  56. os.chdir(path_tep) # 切换路径  
  57. cwd = os.getcwd() # 得到当前工作目录,即当前Python脚本工作的目录路径。  
  58. wlist = os.listdir(cwd)  
  59. for wli in wlist:  
  60.     print(wli)  
  61.   
  62. if os.path.isdir(path_dir_a): # 判断是否文件夹  
  63.     tep_size = os.path.getsize(path_dir_a)    
  64.     print(tep_size)  
  65.   
  66. if os.path.isfile(path_file_a):  
  67.     tep_size = os.path.getsize(path_file_a) # 获得文件大小  
  68.     print(tep_size)  
  69.   
  70. for wroot, wdirs, wfiles in os.walk(path_tep):  
  71.     for wfile in wfiles:  
  72.         file_path = os.path.abspath(wfile) # 获得绝对路径  
  73.         print(file_path)  
  74.   
  75. # 返回文件名  
  76. filename = os.path.basename(path_file_a)  
  77. print(filename)  
  78.   
  79. # 返回文件路径  
  80. dirname = os.path.dirname(path_file_a)  
  81. print(dirname)  
  82.   
  83. # 分割文件名与目录  
  84. # 事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,  
  85. # 同时它不会判断文件或目录是否存在  
  86. (filepath, filename) = os.path.split(path_file_a)  
  87. print(filepath, filename)  
  88. (fname, fext) = os.path.splitext(filename) # 分离文件名与扩展名  
  89. print(fname, fext)  
  90. # 清理文件与文件夹  
  91. del_file(path_file_a)  
  92. del_file(path_file_b)  
  93. del_dir(path_dir_a)  
  94. del_file(path_file_c)  
  95. del_dir(path_dir_b)  


本文参考: http://my.oschina.net/u/131802/blog/61610
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值