全部文章 | 测试技术 | python脚本 | 安全技术 | 项目管理 | 感悟休闲

作者: amions   发表日期: 2007-06-15 13:02   复制链接




1、>>> xxx = file('c:\\a.txt', 'r')

    关键字的第一部分,是文件路径及名称。注意这里面,路径需要用\\ m涜R$mxe  
第二部分,是对文件的模式或者叫权限,一般有以下3种 "r" (read), "w" (write)和 "a"(append).之后,就可以利用 -虡麊}^#…  
xxx_content = infile.read() A撍赺#鼏贠  
xxx_content = infile.readlines() n龒彎d擛2  
来读取文件内容了 鞯鐵j|#C咘  
>>> xxx = file('c:\\a.txt', 'r') Jn糐T 8  
>>> xxx_content = xxx.read()  ZMW駷  
  >>> print xxx_content $s肪!牀L  
      This is line #1

       This is line #2 {2犆Z惪  

       This is line #3 嘼a饻5J  

       END 刚奧){:  

  >>> xxx.close() 笖f茻傠期  

  >>> [翏二V#  

  >>> infile = file('c:\\a.txt', 'r') 煟鼗)┩(  
  >>> xxx = file('c:\\a.txt', 'r') 抵哜CYxh  
  >>> for xxx_line in xxx.readlines(): 7&齤%L  
              print 'Line:', xxx_line

       Line: This is line #1 (嚵|厮!  
       Line: This is line #2 駃?崴虣  
       Line: This is line #3 .Ж(9@寿0  
       Line: END 柢鱽崴=  
   >>> xxx.close() x檚QU訃譝#  
   >>>

苏85{絼  
然后是文件的写入

    >>> xxx=file('c:\\test.txt','w') 顈\u淼札  
    >>> xxx.write('billrice') 喡苃]盓!  
    >>> xxx.write('testtest') )曜侞%X襓  
    >>> xxx.write('enter\n') ;偉hS(湠  
    >>> xxx.writelines(['billrice','ricerice']) 軾灁)Tu灆  
    >>> xxx.close() 澮鸝 }蒒  
    >>> ag牞欶d}  
    >>> xxx=file('c:\\test.txt','r') 3逿u勝X<^  
    >>> content=xxx.read() !辅  
    >>> print content N断 -犼,  
         billricetesttestenter %2歞K疐  
         billricericerice JO$褌牳&  
    >>> 揰唌o铠紁i  
需要注意的是...在xxx.close()之前,c盘下面只有一个空空的test.txt,xxx.close()的作用相当于最后的存盘。

删除文件:

name='c:\1.txt'    瓭t崞T螑  
os.remove(name)

压缩文件:

import os 貶怞峙b穉  
import zipfile .印嘨C`垯  
import time CM哗~ta+m  
# 压缩目录 0哠熄遚  
source_dir  = r'F:\web' 契 Y疫  
# 按时间生成文件名称 呸c ⒓  
target_file = time.strftime('%Y%m%d%H%M%S') + '.zip'

myZipFile = zipfile.ZipFile(target_file, 'w' )# 压缩所有文件,包含子目录 宿_q>m  
for root,dirs,files in os.walk(source_dir): ~憘w'龝  
    for vfileName in files: 郉餻3R  
        fileName = os.path.join(root,vfileName) 2m業叾-  
        myZipFile.write( fileName, fileName, zipfile.ZIP_DEFLATED ) 谀鵕V+  
 # 压缩完成 }0纇C yx  
myZipFile.close()



阅读全文(1183) | 回复(0) | 推送
欢迎到 amions 的个人主页看更多内容



  共0条回复