<i id='1BeSs'><tr id='1BeSs'><dt id='1BeSs'><q id='1BeSs'><span id='1BeSs'><b id='1BeSs'><form id='1BeSs'><ins id='1BeSs'></ins><ul id='1BeSs'></ul><sub id='1BeSs'></sub></form><legend id='1BeSs'></legend><bdo id='1BeSs'><pre id='1BeSs'><center id='1BeSs'></center></pre></bdo></b><th id='1BeSs'></th></span></q></dt></tr></i><div id='1BeSs'><tfoot id='1BeSs'></tfoot><dl id='1BeSs'><fieldset id='1BeSs'></fieldset></dl></div>
    1. <tfoot id='1BeSs'></tfoot>
    2. <legend id='1BeSs'><style id='1BeSs'><dir id='1BeSs'><q id='1BeSs'></q></dir></style></legend>
      • <bdo id='1BeSs'></bdo><ul id='1BeSs'></ul>

      <small id='1BeSs'></small><noframes id='1BeSs'>

        是否在给定目录及其子目录中递归地用Python替换文件中的字符串?

        Replace strings in files by Python, recursively in given directory and its subdirectories?(是否在给定目录及其子目录中递归地用Python替换文件中的字符串?)

        <small id='52CFo'></small><noframes id='52CFo'>

          <bdo id='52CFo'></bdo><ul id='52CFo'></ul>
              <tfoot id='52CFo'></tfoot>

                  <legend id='52CFo'><style id='52CFo'><dir id='52CFo'><q id='52CFo'></q></dir></style></legend>

                • <i id='52CFo'><tr id='52CFo'><dt id='52CFo'><q id='52CFo'><span id='52CFo'><b id='52CFo'><form id='52CFo'><ins id='52CFo'></ins><ul id='52CFo'></ul><sub id='52CFo'></sub></form><legend id='52CFo'></legend><bdo id='52CFo'><pre id='52CFo'><center id='52CFo'></center></pre></bdo></b><th id='52CFo'></th></span></q></dt></tr></i><div id='52CFo'><tfoot id='52CFo'></tfoot><dl id='52CFo'><fieldset id='52CFo'></fieldset></dl></div>

                    <tbody id='52CFo'></tbody>
                • 本文介绍了是否在给定目录及其子目录中递归地用Python替换文件中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  如何在给定目录及其子目录内递归地将文件内的字符串匹配替换为给定的替换?

                  伪码:

                  import os
                  import re
                  from os.path import walk
                  for root, dirs, files in os.walk("/home/noa/Desktop/codes"):
                          for name in dirs:
                                  re.search("dbname=noa user=noa", "dbname=masi user=masi")
                                     // I am trying to replace here a given match in a file
                  

                  推荐答案

                  将所有这些代码放入名为mass_replace的文件中。在Linux或MacOSX上,您可以执行chmod +x mass_replace,然后只需运行以下命令。在Windows下,您可以使用python mass_replace后跟适当的参数来运行它。

                  #!/usr/bin/python
                  
                  import os
                  import re
                  import sys
                  
                  # list of extensions to replace
                  DEFAULT_REPLACE_EXTENSIONS = None
                  # example: uncomment next line to only replace *.c, *.h, and/or *.txt
                  # DEFAULT_REPLACE_EXTENSIONS = (".c", ".h", ".txt")
                  
                  def try_to_replace(fname, replace_extensions=DEFAULT_REPLACE_EXTENSIONS):
                      if replace_extensions:
                          return fname.lower().endswith(replace_extensions)
                      return True
                  
                  
                  def file_replace(fname, pat, s_after):
                      # first, see if the pattern is even in the file.
                      with open(fname) as f:
                          if not any(re.search(pat, line) for line in f):
                              return # pattern does not occur in file so we are done.
                  
                      # pattern is in the file, so perform replace operation.
                      with open(fname) as f:
                          out_fname = fname + ".tmp"
                          out = open(out_fname, "w")
                          for line in f:
                              out.write(re.sub(pat, s_after, line))
                          out.close()
                          os.rename(out_fname, fname)
                  
                  
                  def mass_replace(dir_name, s_before, s_after, replace_extensions=DEFAULT_REPLACE_EXTENSIONS):
                      pat = re.compile(s_before)
                      for dirpath, dirnames, filenames in os.walk(dir_name):
                          for fname in filenames:
                              if try_to_replace(fname, replace_extensions):
                                  fullname = os.path.join(dirpath, fname)
                                  file_replace(fullname, pat, s_after)
                  
                  if len(sys.argv) != 4:
                      u = "Usage: mass_replace <dir_name> <string_before> <string_after>
                  "
                      sys.stderr.write(u)
                      sys.exit(1)
                  
                  mass_replace(sys.argv[1], sys.argv[2], sys.argv[3])
                  

                  编辑:我已将上述代码从原始答案更改。有几个变化。首先,mass_replace()现在调用re.compile()预编译搜索模式;其次,为了检查文件的扩展名是什么,我们现在向.endswith()传递文件扩展名元组,而不是调用.endswith()三次;第三,它现在使用最新版本的Python中提供的with语句;最后,file_replace()现在检查是否在文件中找到该模式,如果(旧版本会重写每个文件,即使输出文件与输入文件相同也会更改时间戳;这很不雅观。)

                  edit:我将其更改为默认替换每个文件,但是您可以使用一行代码进行编辑,以将其限制为特定的扩展名。我认为替换每个文件是更有用的开箱即用的默认设置。可以使用不接触的扩展名或文件名列表、不区分大小写的选项等对其进行扩展。

                  编辑:@asciimo在评论中指出了一个错误。我对此进行了编辑以修复错误。str.endswith()记录为接受要尝试的字符串元组,但不接受列表。已修复。另外,我让两个函数接受一个可选参数,以允许您传入一个扩展元组;修改此参数以接受命令行参数以指定哪些扩展应该非常容易。

                  这篇关于是否在给定目录及其子目录中递归地用Python替换文件中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Split a Pandas column of lists into multiple columns(将 Pandas 的列表列拆分为多列)
                  How does the @property decorator work in Python?(@property 装饰器在 Python 中是如何工作的?)
                  What is the difference between old style and new style classes in Python?(Python中的旧样式类和新样式类有什么区别?)
                  How to break out of multiple loops?(如何打破多个循环?)
                  How to put the legend out of the plot(如何将传说从情节中剔除)
                  Why is the output of my function printing out quot;Nonequot;?(为什么我的函数输出打印出“无?)

                  1. <i id='4J3f4'><tr id='4J3f4'><dt id='4J3f4'><q id='4J3f4'><span id='4J3f4'><b id='4J3f4'><form id='4J3f4'><ins id='4J3f4'></ins><ul id='4J3f4'></ul><sub id='4J3f4'></sub></form><legend id='4J3f4'></legend><bdo id='4J3f4'><pre id='4J3f4'><center id='4J3f4'></center></pre></bdo></b><th id='4J3f4'></th></span></q></dt></tr></i><div id='4J3f4'><tfoot id='4J3f4'></tfoot><dl id='4J3f4'><fieldset id='4J3f4'></fieldset></dl></div>
                        <tbody id='4J3f4'></tbody>
                      <legend id='4J3f4'><style id='4J3f4'><dir id='4J3f4'><q id='4J3f4'></q></dir></style></legend>
                      <tfoot id='4J3f4'></tfoot>

                          <small id='4J3f4'></small><noframes id='4J3f4'>

                          • <bdo id='4J3f4'></bdo><ul id='4J3f4'></ul>