python实现的用于搜索文件并进行内容替换的类实例,测试可用
分类:多线程

python实现的用于搜索文件并进行内容替换的类实例,

本文实例讲述了python实现的用于搜索文件并进行内容替换的类。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python -O
# coding: UTF-8
"""
-replace string in files (recursive)
-display the difference.
v0.2
 - search_string can be a re.compile() object -> use re.sub for replacing
v0.1
 - initial version
  Useable by a small "client" script, e.g.:
-------------------------------------------------------------------------------
#!/usr/bin/python -O
# coding: UTF-8
import sys, re
#sys.path.insert(0,"/path/to/git/repro/") # Please change path
from replace_in_files import SearchAndReplace
SearchAndReplace(
  search_path = "/to/the/files/",
  # e.g.: simple string replace:
  search_string = 'the old string',
  replace_string = 'the new string',
  # e.g.: Regular expression replacing (used re.sub)
  #search_string = re.compile('{% url (.*?) %}'),
  #replace_string = "{% url 'g<1>' %}",
  search_only = True, # Display only the difference
  #search_only = False, # write the new content
  file_filter=("*.py",), # fnmatch-Filter
)
-------------------------------------------------------------------------------
:copyleft: 2009-2011 by Jens Diemer
"""
__author__ = "Jens Diemer"
__license__ = """GNU General Public License v3 or above -
 http://www.opensource.org/licenses/gpl-license.php"""
__url__ = "http://www.jensdiemer.de"
__version__ = "0.2"
import os, re, time, fnmatch, difflib
# FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
RE_TYPE = type(re.compile(""))
class SearchAndReplace(object):
  def __init__(self, search_path, search_string, replace_string,
                    search_only=True, file_filter=("*.*",)):
    self.search_path = search_path
    self.search_string = search_string
    self.replace_string = replace_string
    self.search_only = search_only
    self.file_filter = file_filter
    assert isinstance(self.file_filter, (list, tuple))
    # FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
    self.is_re = isinstance(self.search_string, RE_TYPE)
    print "Search '%s' in [%s]..." % (
      self.search_string, self.search_path
    )
    print "_" * 80
    time_begin = time.time()
    file_count = self.walk()
    print "_" * 80
    print "%s files searched in %0.2fsec." % (
      file_count, (time.time() - time_begin)
    )
  def walk(self):
    file_count = 0
    for root, dirlist, filelist in os.walk(self.search_path):
      if ".svn" in root:
        continue
      for filename in filelist:
        for file_filter in self.file_filter:
          if fnmatch.fnmatch(filename, file_filter):
            self.search_file(os.path.join(root, filename))
            file_count += 1
    return file_count
  def search_file(self, filepath):
    f = file(filepath, "r")
    old_content = f.read()
    f.close()
    if self.is_re or self.search_string in old_content:
      new_content = self.replace_content(old_content, filepath)
      if self.is_re and new_content == old_content:
        return
      print filepath
      self.display_plaintext_diff(old_content, new_content)
  def replace_content(self, old_content, filepath):
    if self.is_re:
      new_content = self.search_string.sub(self.replace_string, old_content)
      if new_content == old_content:
        return old_content
    else:
      new_content = old_content.replace(
        self.search_string, self.replace_string
      )
    if self.search_only != False:
      return new_content
    print "Write new content into %s..." % filepath,
    try:
      f = file(filepath, "w")
      f.write(new_content)
      f.close()
    except IOError, msg:
      print "Error:", msg
    else:
      print "OK"
    print
    return new_content
  def display_plaintext_diff(self, content1, content2):
    """
    Display a diff.
    """
    content1 = content1.splitlines()
    content2 = content2.splitlines()
    diff = difflib.Differ().compare(content1, content2)
    def is_diff_line(line):
      for char in ("-", "+", "?"):
        if line.startswith(char):
          return True
      return False
    print "line | textn-------------------------------------------"
    old_line = ""
    in_block = False
    old_lineno = lineno = 0
    for line in diff:
      if line.startswith(" ") or line.startswith("+"):
        lineno += 1
      if old_lineno == lineno:
        display_line = "%4s | %s" % ("", line.rstrip())
      else:
        display_line = "%4s | %s" % (lineno, line.rstrip())
      if is_diff_line(line):
        if not in_block:
          print "..."
          # Display previous line
          print old_line
          in_block = True
        print display_line
      else:
        if in_block:
          # Display the next line aber a diff-block
          print display_line
        in_block = False
      old_line = display_line
      old_lineno = lineno
    print "..."
if __name__ == "__main__":
  SearchAndReplace(
    search_path=".",
    # e.g.: simple string replace:
    search_string='the old string',
    replace_string='the new string',
    # e.g.: Regular expression replacing (used re.sub)
    #search_string  = re.compile('{% url (.*?) %}'),
    #replace_string = "{% url 'g<1>' %}",
    search_only=True, # Display only the difference
#    search_only   = False, # write the new content
    file_filter=("*.py",), # fnmatch-Filter
  )

希望本文所述对大家的Python程序设计有所帮助。

本文实例讲述了python实现的用于搜索文件并进行内容替换的类。分享给大家供大家参考...

python实现搜索本地文件信息写入文件的方法,

本文实例讲述了python实现搜索本地文件信息写入文件的方法。分享给大家供大家参考,具体如下:

主要功能:

在指定的盘符,如D盘,搜索出与用户给定后缀名(如:jpg,png)相关的文件,然后把搜索出来的信息(相关文件的绝对路径),存放到用户指定的文件(如果文件不存在,则建立相应的文件)中

先卡看运行效果吧:

运行效果的前部分:

图片 1

运行效果的后部分:

图片 2

写入信息后的文件:

图片 3

代码部分:

#在指定的盘符,如D盘,搜索出与用户给定后缀名(如:jpg,png)相关的文件
#然后把搜索出来的信息(相关文件的绝对路径),存放到用户指定的
#文件(如果文件不存在,则建立相应的文件)中
import os
import time
#指定盘符
DESK = 'E:\'
#信息保存文件的路径
##########    这里请先建立好此文件,我在做文件操作的过程中
##########    使用os.mknod('E:\info.txt'),系统不会建立文件的
SAVE_FILE = 'E:\info.txt'
#文件后缀类型
FILE_EXT = ['bmp','jpeg','gif','psd','png','jpg']
#定义全局变量
my_dirs = []
my_files = []
#文件个数
FILES_NUMBER = 0
#符合要求的文件个数
RIGHT_FILES_NUMBER = 0
#不符合要求的文件个数
NOT_RIGHT_FILES_NUMBER = 0
#文件夹个数
DIR_NUMBER = 0
#获取指定文件夹下面的所有文件及文件夹
#如果指定的文件夹不存在,则返回相应的提示信息
def listdir(dir_path):
  if os.path.exists(dir_path):
    return os.listdir(dir_path)
  else:
    return '目录'+ dir_path + '不存在'
#搜索文件主函数
def search_files(path,name):
  if not os.path.isdir(path) and not os.path.isfile(path):
    return False
  path = os.path.join(path,name)
  if os.path.isfile(path): #是文件
    global FILES_NUMBER
    FILES_NUMBER = FILES_NUMBER + 1
    lists = path.split('.')
    #print('============================================',lists)
    file_ext = lists[-1] #文件扩展名
    if file_ext in FILE_EXT:
      global RIGHT_FILES_NUMBER
      RIGHT_FILES_NUMBER = RIGHT_FILES_NUMBER + 1
      global my_files
      now = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
      size = str(get_file_size(path))
      my_files.append(now+'  '+path+'  '+size+'n')
      print('文件:',path)
    else:
      global NOT_RIGHT_FILES_NUMBER
      NOT_RIGHT_FILES_NUMBER = NOT_RIGHT_FILES_NUMBER + 1
  elif os.path.isdir(path): #是文件夹
    global DIR_NUMBER
    DIR_NUMBER = DIR_NUMBER + 1
    for name in listdir(path):
      #print(os.path.join(path,name))
      search_files(path,name)
#获取文件大小
def get_file_size(path):
  if os.path.exists(path):
    return os.path.getsize(path)
#写入信息
def write_info(content):
  if os.path.exists(path):
    with open(SAVE_FILE,'w+') as fp:
      fp.write(content)
      fp.flush()
      fp.close()
  else:
    print('文件:{}不存在!'.format(SAVE_FILE))
#读取所有信息
def read_info():
  if os.path.exists(path):
    with open(SAVE_FILE,'r+') as fp:
      for line in fp:
        print(line)
  else:
    print('文件:{}不存在!'.format(SAVE_FILE))
if __name__ == '__main__':
  for d in listdir(DESK):
    my_dirs.append(os.path.join(DESK,d))
  print(my_dirs)
  #这里是做测试用的,由于扫描整个盘符涉及到的文件和文件夹很多,可能要花一定的时间
  #所以这里可以使用一个文件夹作为测试
  my_dir = ['E:\test']
  for path in my_dir:
    search_files(path,'')
  print('#' * 50)
  print(my_files)
  print('#' * 50)
  print('开始写入信息...')
  content = ''.join(my_files)
  write_info(content)
  print('#' * 50)
  print('开始读取信息...')
  read_info()
  print('#' * 50)
  print('搜索文件夹总数:{0},文件总数:{1}'.format(DIR_NUMBER,FILES_NUMBER))
  print('符合要求的文件总数:{0},不符合要求的文件总数:{1}'.format(RIGHT_FILES_NUMBER,NOT_RIGHT_FILES_NUMBER))

运行控制台情况;

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
['E:\bb', 'E:\devlopment', 'E:\game', 'E:\hongten_download', 'E:\info.txt', 'E:\log4j', 'E:\mydir', 'E:\oracle', 'E:\oracle10.2_win32', 'E:\RECYCLER', 'E:\svn_checkout', 'E:\System Volume Information', 'E:\test', 'E:\The KMPlayer', 'E:\windows', 'E:\work']
文件: E:test20130627_140132Hongten.jpg
文件: E:test20130627_182913(1)Hongten.jpg
文件: E:test20130627_183008(1)Hongten.jpg
文件: E:test20130627_183054Hongten.jpg
文件: E:test20130627_183059Hongten.jpg
文件: E:test20130627_183101Hongten.jpg
文件: E:test20130627_183116Hongten.jpg
文件: E:test20130627_183326Hongten.jpg
文件: E:test20130627_183714Hongten.jpg
文件: E:test20130627_183749Hongten.jpg
文件: E:test20130627_183925Hongten.jpg
文件: E:test20130627_203658Hongten.jpg
文件: E:test20130627_203802Hongten.jpg
文件: E:test20130627_205112(1)Hongten.jpg
文件: E:test20130627_205131Hongten.jpg
文件: E:test20130627_205159Hongten.jpg
文件: E:test20130627_205219(1)Hongten.jpg
文件: E:test20130627_205257Hongten.jpg
文件: E:test20130627_205315Hongten.jpg
文件: E:test20130627_205408(1)Hongten.jpg
文件: E:test20130627_205425Hongten.jpg
文件: E:test20130627_205627Hongten.jpg
文件: E:test20130627_205629Hongten.jpg
文件: E:testhongten6.2720130627_140132Hongten.jpg
文件: E:testhongten6.2720130627_182913(1)Hongten.jpg
文件: E:testhongten6.2720130627_183008(1)Hongten.jpg
文件: E:testhongten6.2720130627_183054Hongten.jpg
文件: E:testhongten6.2720130627_183059Hongten.jpg
文件: E:testhongten6.2720130627_183101Hongten.jpg
文件: E:testhongten6.2720130627_183116Hongten.jpg
文件: E:testhongten6.2720130627_183326Hongten.jpg
文件: E:testhongten6.2720130627_183714Hongten.jpg
文件: E:testhongten6.2720130627_183749Hongten.jpg
文件: E:testhongten6.2720130627_183925Hongten.jpg
文件: E:testhongten6.2720130627_203658Hongten.jpg
文件: E:testhongten6.2720130627_203802Hongten.jpg
文件: E:testhongten6.2720130627_205112(1)Hongten.jpg
文件: E:testhongten6.2720130627_205131Hongten.jpg
文件: E:testhongten6.2720130627_205159Hongten.jpg
文件: E:testhongten6.2720130627_205219(1)Hongten.jpg
文件: E:testhongten6.2720130627_205257Hongten.jpg
文件: E:testhongten6.2720130627_205315Hongten.jpg
文件: E:testhongten6.2720130627_205408(1)Hongten.jpg
文件: E:testhongten6.2720130627_205425Hongten.jpg
文件: E:testhongten6.2720130627_205627Hongten.jpg
文件: E:testhongten6.2720130627_205629Hongten.jpg
##################################################
['2013-07-28 17:14:49  E:\test\20130627_140132Hongten.jpg  0n', '2013-07-28 17:14:49  E:\test\20130627_182913(1)Hongten.jpg  2380747n', '2013-07-28 17:14:49  E:\test\20130627_183008(1)Hongten.jpg  2315326n', '2013-07-28 17:14:49  E:\test\20130627_183054Hongten.jpg  2672977n', '2013-07-28 17:14:49  E:\test\20130627_183059Hongten.jpg  2006608n', '2013-07-28 17:14:49  E:\test\20130627_183101Hongten.jpg  2076974n', '2013-07-28 17:14:49  E:\test\20130627_183116Hongten.jpg  2687018n', '2013-07-28 17:14:49  E:\test\20130627_183326Hongten.jpg  1993448n', '2013-07-28 17:14:49  E:\test\20130627_183714Hongten.jpg  2497973n', '2013-07-28 17:14:49  E:\test\20130627_183749Hongten.jpg  2066327n', '2013-07-28 17:14:49  E:\test\20130627_183925Hongten.jpg  2037776n', '2013-07-28 17:14:49  E:\test\20130627_203658Hongten.jpg  3033996n', '2013-07-28 17:14:49  E:\test\20130627_203802Hongten.jpg  2837396n', '2013-07-28 17:14:49  E:\test\20130627_205112(1)Hongten.jpg  2987659n', '2013-07-28 17:14:49  E:\test\20130627_205131Hongten.jpg  2745724n', '2013-07-28 17:14:49  E:\test\20130627_205159Hongten.jpg  2824810n', '2013-07-28 17:14:49  E:\test\20130627_205219(1)Hongten.jpg  2864744n', '2013-07-28 17:14:49  E:\test\20130627_205257Hongten.jpg  3092656n', '2013-07-28 17:14:49  E:\test\20130627_205315Hongten.jpg  2832393n', '2013-07-28 17:14:49  E:\test\20130627_205408(1)Hongten.jpg  2796261n', '2013-07-28 17:14:49  E:\test\20130627_205425Hongten.jpg  3295286n', '2013-07-28 17:14:49  E:\test\20130627_205627Hongten.jpg  2819717n', '2013-07-28 17:14:49  E:\test\20130627_205629Hongten.jpg  2813522n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_140132Hongten.jpg  2571032n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_182913(1)Hongten.jpg  2380747n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183008(1)Hongten.jpg  2315326n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183054Hongten.jpg  2672977n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183059Hongten.jpg  2006608n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183101Hongten.jpg  2076974n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183116Hongten.jpg  2687018n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183326Hongten.jpg  1993448n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183714Hongten.jpg  2497973n', '2013-07-28 17:14:49  E:\test\hongten\6.27\20130627_183749Hongten.jpg  2066327n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_183925Hongten.jpg  2037776n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_203658Hongten.jpg  3033996n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_203802Hongten.jpg  2837396n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205112(1)Hongten.jpg  2987659n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205131Hongten.jpg  2745724n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205159Hongten.jpg  2824810n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205219(1)Hongten.jpg  2864744n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205257Hongten.jpg  3092656n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205315Hongten.jpg  2832393n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205408(1)Hongten.jpg  2796261n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205425Hongten.jpg  3295286n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205627Hongten.jpg  2819717n', '2013-07-28 17:14:50  E:\test\hongten\6.27\20130627_205629Hongten.jpg  2813522n']
##################################################
开始写入信息...
##################################################
开始读取信息...
2013-07-28 17:14:49  E:test20130627_140132Hongten.jpg  0
2013-07-28 17:14:49  E:test20130627_182913(1)Hongten.jpg  2380747
2013-07-28 17:14:49  E:test20130627_183008(1)Hongten.jpg  2315326
2013-07-28 17:14:49  E:test20130627_183054Hongten.jpg  2672977
2013-07-28 17:14:49  E:test20130627_183059Hongten.jpg  2006608
2013-07-28 17:14:49  E:test20130627_183101Hongten.jpg  2076974
2013-07-28 17:14:49  E:test20130627_183116Hongten.jpg  2687018
2013-07-28 17:14:49  E:test20130627_183326Hongten.jpg  1993448
2013-07-28 17:14:49  E:test20130627_183714Hongten.jpg  2497973
2013-07-28 17:14:49  E:test20130627_183749Hongten.jpg  2066327
2013-07-28 17:14:49  E:test20130627_183925Hongten.jpg  2037776
2013-07-28 17:14:49  E:test20130627_203658Hongten.jpg  3033996
2013-07-28 17:14:49  E:test20130627_203802Hongten.jpg  2837396
2013-07-28 17:14:49  E:test20130627_205112(1)Hongten.jpg  2987659
2013-07-28 17:14:49  E:test20130627_205131Hongten.jpg  2745724
2013-07-28 17:14:49  E:test20130627_205159Hongten.jpg  2824810
2013-07-28 17:14:49  E:test20130627_205219(1)Hongten.jpg  2864744
2013-07-28 17:14:49  E:test20130627_205257Hongten.jpg  3092656
2013-07-28 17:14:49  E:test20130627_205315Hongten.jpg  2832393
2013-07-28 17:14:49  E:test20130627_205408(1)Hongten.jpg  2796261
2013-07-28 17:14:49  E:test20130627_205425Hongten.jpg  3295286
2013-07-28 17:14:49  E:test20130627_205627Hongten.jpg  2819717
2013-07-28 17:14:49  E:test20130627_205629Hongten.jpg  2813522
2013-07-28 17:14:49  E:testhongten6.2720130627_140132Hongten.jpg  2571032
2013-07-28 17:14:49  E:testhongten6.2720130627_182913(1)Hongten.jpg  2380747
2013-07-28 17:14:49  E:testhongten6.2720130627_183008(1)Hongten.jpg  2315326
2013-07-28 17:14:49  E:testhongten6.2720130627_183054Hongten.jpg  2672977
2013-07-28 17:14:49  E:testhongten6.2720130627_183059Hongten.jpg  2006608
2013-07-28 17:14:49  E:testhongten6.2720130627_183101Hongten.jpg  2076974
2013-07-28 17:14:49  E:testhongten6.2720130627_183116Hongten.jpg  2687018
2013-07-28 17:14:49  E:testhongten6.2720130627_183326Hongten.jpg  1993448
2013-07-28 17:14:49  E:testhongten6.2720130627_183714Hongten.jpg  2497973
2013-07-28 17:14:49  E:testhongten6.2720130627_183749Hongten.jpg  2066327
2013-07-28 17:14:50  E:testhongten6.2720130627_183925Hongten.jpg  2037776
2013-07-28 17:14:50  E:testhongten6.2720130627_203658Hongten.jpg  3033996
2013-07-28 17:14:50  E:testhongten6.2720130627_203802Hongten.jpg  2837396
2013-07-28 17:14:50  E:testhongten6.2720130627_205112(1)Hongten.jpg  2987659
2013-07-28 17:14:50  E:testhongten6.2720130627_205131Hongten.jpg  2745724
2013-07-28 17:14:50  E:testhongten6.2720130627_205159Hongten.jpg  2824810
2013-07-28 17:14:50  E:testhongten6.2720130627_205219(1)Hongten.jpg  2864744
2013-07-28 17:14:50  E:testhongten6.2720130627_205257Hongten.jpg  3092656
2013-07-28 17:14:50  E:testhongten6.2720130627_205315Hongten.jpg  2832393
2013-07-28 17:14:50  E:testhongten6.2720130627_205408(1)Hongten.jpg  2796261
2013-07-28 17:14:50  E:testhongten6.2720130627_205425Hongten.jpg  3295286
2013-07-28 17:14:50  E:testhongten6.2720130627_205627Hongten.jpg  2819717
2013-07-28 17:14:50  E:testhongten6.2720130627_205629Hongten.jpg  2813522
##################################################
搜索文件夹总数:4,文件总数:50
符合要求的文件总数:46,不符合要求的文件总数:4
>>> 

希望本文所述对大家Python程序设计有所帮助。

本文实例讲述了Python实现的本地文件搜索功能。分享给大家供大家参考,具体如下:

本文实例讲述了Python实现替换文件中指定内容的方法。分享给大家供大家参考,具体如下:

您可能感兴趣的文章:

  • python实现的用于搜索文件并进行内容替换的类实例
  • python开发之基于thread线程搜索本地文件的方法
  • python实现搜索指定目录下文件及文件内搜索指定关键词的方法
  • Python3搜索及替换文件中文本的方法
  • python使用正则搜索字符串或文件中的浮点数代码实例
  • python将多个文本文件合并为一个文本的代码(便于搜索)
  • Python写入CSV文件的方法
  • Python3写入文件常用方法实例分析
  • 在Python程序中进行文件读取和写入操作的教程
  • Python中使用第三方库xlrd来写入Excel文件示例
  • python进阶教程之文本文件的读取和写入

本文实例讲述了python实现搜索本地文件信息写入文件的方法。分享给大家供大家参考,具体如...

偶尔需要搜索指定文件,不想每次都在windows下面去搜索,想用代码来实现搜索,而且能够收集搜索结果,于是有了下面的代码。

这里使用python编写的程序,实现如下功能:将文件中的指定子串 修改为 另外的子串

# -*- coding:utf-8 -*-
#! python2
import os
def search_file(fileNmae, path):
  '''search a file in target directory
  :param fileNmae: file to be searched
  :param path: search scope
  :return:file list
  '''
  flag = False
  count = 0
  result_list = []
  if os.path.exists(path):
    for root, dirs, files in os.walk(path):
      for fn in files:
        Name = fn.decode('gbk')
        cu_path = root.encode('gbk')+"\"+Name
        if Name.lower().find(fileNmae.lower()) != -1 and os.path.isfile(cu_path):
          print ":::Find it,file no", count+1, ":", cu_path
          flag = True
          count += 1
          result_list.append(cu_path)
    if flag is False:
      print ":::Not found the file:", fileNmae, "in path:", path
    else:
      print "======== Get[", count, "]files ========"
      return result_list
  else:
    print "!!-----path not existed:", path
#测试:
search_file("4.jpg", "C:\img")

编写的python程序,文件名是file_replace.py,具体代码如下:

运行结果:

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys,os
if len(sys.argv)<4 or len(sys.argv)>5:
 sys.exit('There needs four or five parameters')
elif len(sys.argv)==4:
 print 'usage:./file_replace.py old_text new_text filename'
else:
 print 'usage:./file_replace.py old_text new_text filename --bak'
old_text,new_text=sys.argv[1],sys.argv[2]
file_name=sys.argv[3]
f=file(file_name,'rb')
new_file=file('.%s.bak' % file_name,'wb')#文件名以.开头的文件是隐藏文件
for line in f.xreadlines():#f.xreadlines()返回一个文件迭代器,每次只从文件(硬盘)中读一行
 new_file.write(line.replace(old_text,new_text))
f.close()
new_file.close()
if '--bak' in sys.argv: #'--bak'表示要求对原文件备份
 os.rename(file_name,'%s.bak' % file_name) #unchanged
 os.rename('.%s.bak' % file_name,file_name) #changed
else:
 os.rename(file_name,'wahaha.txt')#此处也可以将原文件删除,以便下一语句能够正常执行
 os.rename('.%s.bak' % file_name,file_name)

图片 4

下面是代码执行的一个例子:

更多Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

song@ubuntu:~$ more hello.txt
Hello python
Hello world
python Hello
world Hello
song@ubuntu:~$ python file_replace.py Hello love hello.txt --bak
usage:./file_replace.py old_text new_text filename --bak
song@ubuntu:~$ ls
Desktop Documents  file_replace.py Music systemExit.py
diff1.txt Downloads  hello.txt Pictures Templates
diff.txt examples.desktop hello.txt.bak Public Videos
song@ubuntu:~$ more hello.txt
love python
love world
python love
world love
song@ubuntu:~$ more hello.txt.bak
Hello python
Hello world
python Hello
world Hello
song@ubuntu:~$

希望本文所述对大家Python程序设计有所帮助。

更多Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

您可能感兴趣的文章:

  • python实现搜索本地文件信息写入文件的方法
  • python开发之基于thread线程搜索本地文件的方法
  • python实现的用于搜索文件并进行内容替换的类实例
  • python实现搜索指定目录下文件及文件内搜索指定关键词的方法
  • Python3搜索及替换文件中文本的方法
  • python使用正则搜索字符串或文件中的浮点数代码实例
  • python将多个文本文件合并为一个文本的代码(便于搜索)
  • python实现搜索文本文件内容脚本

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

  • python批量替换多文件字符串问题详解
  • python实现文件名批量替换和内容替换
  • Python3搜索及替换文件中文本的方法
  • python 读取文件并替换字段的实例

本文由10bet手机官网发布于多线程,转载请注明出处:python实现的用于搜索文件并进行内容替换的类实例,测试可用

上一篇:没有了 下一篇:python实现域名系统,基本用法实例分析
猜你喜欢
热门排行
精彩图文