Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1504316
  • 博文数量: 164
  • 博客积分: 2993
  • 博客等级: 少校
  • 技术积分: 1718
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-24 11:42
文章分类

全部博文(164)

文章存档

2014年(1)

2013年(36)

2012年(90)

2011年(37)

分类: Python/Ruby

2013-10-23 11:35:56

1.遍历文件夹
  1. import os
  2. import os.path
  3. rootdir = “d:\data” # 指明被遍历的文件夹

  4. for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
  5.     for dirname in dirnames: #输出文件夹信息
  6.      print "parent is:" + parent
  7.      print "dirname is" + dirname

  8.     for filename in filenames: #输出文件信息
  9.      print "parent is": + parent
  10.      print "filename is:" + filename
  11.    print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息

  12.                                                                          #windows下为:d:\data\query_text\EL_00154
2.查找中文字符

  1. import re
  2. pchinese=re.compile(ur'([\u4e00-\u9fa5]+)+?') #判断是否为中文的正则表达式
  3. f=open("D:\\workspace\\saas\\core\\admin\\controller\\sale\\ctl.tools.php") #打开要提取的文件
  4. fw=open("getdata.txt","w")#打开要写入的文件
  5. for line in f.readlines(): #循环读取要读取文件的每一行
  6.     m=pchinese.findall(line.decode('utf8')) #使用正则表达获取中文
  7.     if m:
  8.         str1='|'.join(m)#同行的中文用竖杠区分
  9.         str2=str1
  10.         fw.write(str2)#写入文件
  11.         fw.write("\n")#不同行的要换行
  12. f.close()
  13. fw.close()#

3.遍历文件夹,并将文件中中文写入文件

  1. #coding=utf-8

  2. import re, os
  3. def find_chn(infile, outfile):
  4.     pchinese=re.compile(ur'([\u4e00-\u9fa5]+)+?') #判断是否为中文的正则表达式
  5.     f=open(infile) #打开要提取的文件
  6.     flag = 0
  7.     for line in f.readlines(): #循环读取要读取文件的每一行
  8.         if line.find('//')!= -1:#如果有注释,直接跳过
  9.             continue
  10.         if line.find('/*')!= -1 or line.find('')!= -1:
  11.             flag = 0
  12.             continue
  13.         if flag==1:
  14.             continue
  15.         m=pchinese.findall(line.decode('utf8')) #使用正则表达获取中文
  16.         if m:
  17.             str1='|'.join(m)#同行的中文用竖杠区分
  18.             str2=str1
  19.             outfile.write(str2)#写入文件
  20.             outfile.write("\n")#不同行的要换行
  21.             print str2
  22.     f.close()


  23. fw=open("getdata.txt","a+")#打开要写入的文件
  24. for parent,dirnames,filenames in os.walk("D:\\workspace\\saas\\core\\shop\\view\\gallery\\"): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字

  25.     for filename in filenames: #输出文件信息
  26.         print os.path.join(parent,filename)
  27.         find_chn(os.path.join(parent,filename), fw)

  28. fw.close()#



阅读(4212) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~