【问题标题】:Batch replace strings in files with Python用 Python 批量替换文件中的字符串
【发布时间】:2016-07-13 15:17:52
【问题描述】:

所以我正在尝试创建一个 Python 脚本,该脚本将查看 *.styles*.layout 文件并替换这些文件中的特定字符串。我已经尝试了很多东西,但我无法弄清楚我应该做什么,甚至在网上查看其他代码示例只会让人更加难以理解。

这是我目前在我的代码中的内容;

#!/usr/bin/python3
# coding: utf-8

import os
import sys
import fileinput

f1 = open ('*.styles', 'r') # read *.styles
f2 = open ('*.styles', 'w') # write *.styles
f3 = open ('*.layout', 'r') # read *.layout
f4 = open ('*.layout', 'w') # write *.layout
for line in f1:
    f2.write(line.replace('font-size=15','font-size=12'))  # replace string for
    f2.write(line.replace('font-size=14','font-size=12'))  # files in *.styles
    f2.write(line.replace('font-size=18','font-size=14'))
    f2.write(line.replace('font-size=30','font-size=18'))
    f2.write(line.replace('font-size=36','font-size=18'))
    f2.write(line.replace('font-size=16','font-size=12'))
    f2.write(line.replace('font-size=26','font-size=16'))
    f2.write(line.replace('font-size=48','font-size=20'))
    f2.write(line.replace('font-size=28','font-size=16'))
    f2.write(line.replace('font-size=17','font-size=14'))
    f2.write(line.replace('font-size=21','font-size=14'))
f1.close()
f2.close()

for line in f3:
    f4.write(line.replace('font-size=15','font-size=12'))  # replace string for
    f4.write(line.replace('font-size=14','font-size=12'))  # files in *.layout
    f4.write(line.replace('font-size=18','font-size=14'))
    f4.write(line.replace('font-size=30','font-size=18'))
    f4.write(line.replace('font-size=36','font-size=18'))
    f4.write(line.replace('font-size=16','font-size=12'))
    f4.write(line.replace('font-size=26','font-size=16'))
    f4.write(line.replace('font-size=48','font-size=20'))
    f4.write(line.replace('font-size=28','font-size=16'))
    f4.write(line.replace('font-size=17','font-size=14'))
    f4.write(line.replace('font-size=21','font-size=14'))
f3.close()
f4.close()

print ("\n\n ## Done!\n\n")
sys.exit(0)

我确实想包含一个 “你想提交更改吗?[Y/n]” 并带有一个简单的是/否用户输入答案,但这有点太复杂而无法弄清楚带有While True:While False: 语句。

当这段代码在我想测试的文件上测试运行时,它只会显示一个错误;

line 8, in <module>
    f1 = open ('*.styles', 'r') # read *.styles
FileNotFoundError: [Errno 2] No such file or directory: '*.styles'

我只是希望能够像这样从命令行运行;

$ string_search.py .

因此它会更改当前目录中包含该目录中*.styles*.layout 文件的所有文件,因此您不必指定实际目录,只需在当前目录和文件夹中。

【问题讨论】:

  • 当您的问题归结为导致问题的一行代码时,我不知道您为什么包含有关字符串搜索和 while 循环以及其他所有内容的所有这些信息。请尝试在每个帖子中坚持一个问题并使用最小可验证的示例。
  • @Two-BitAlchemist - 你没有抓住重点,这是一个问题。主要问题是如何让 Python 搜索指定的每个文件,并将这些特定文件中的指定字符串替换为我想要替换的新字符串。它归结为一个快速简单的解决方案,可以通过快速提交更改来处理许多文件,从而节省了单独浏览每个文件的时间。
  • @user94959:如果您拆分问题,您可以更轻松地获得有用的答案: 1. 如何在 Python 中获取匹配文件的列表? 2、如何在Python中对单个文件进行字符串替换,将结果写回到同一个文件中?
  • @user94959 实际上你没有抓住重点。您的所有其他代码都有效。什么不起作用是您尝试执行的操作以处理与 glob 模式匹配的多个文件。这就是为什么你得到 3 个与字符串替换无关的答案。

标签: python file file-io helpers


【解决方案1】:

正如 Scott Hunter 所写,open 打开一个文件。您需要获取匹配文件的列表,并在循环中为每个文件分别调用open。这是怎么做的。

创建一个处理单个文件的函数:

def process_file(filename):
  print(filename)
  # ... open(filename) ...
  # ... open(filename, 'w') ...

然后像这样调用函数:

import glob
for filename in glob.glob('*.styles'):
  process_file(filename)

或者像这样,递归枚举目录和文件:

import os
for dirpath, dirnames, filenames in os.walk('.'):
  for filename in filenames:
    # Instead of .endswith, you can use the fnmatch module to match on '*.styles'.
    if filename.endswith('.styles'):
      process_file(os.path.join(dirpath, filename))

【讨论】:

    【解决方案2】:

    open 打开单个文件;您似乎正在尝试使用它来打开与模式匹配的文件集合。也许您想查看os.walk 来遍历文件目录,以便您可以单独处理每个文件。

    【讨论】:

      【解决方案3】:

      我不得不这样做。 我使用fileinput.input 进行管理,例如: 首先我会迭代文件然后修改它们:

      for current_path, dirs, files in os.walk(Your_Path_With_Files)):
                  for file in files:
                      if file.endswith('.styles'):
                         #here you store the file path somewhere
                         #I'm not 100% the exact way to have the full path,
                         # but it's with os.path.join() to have a clean path
                         #list_path_styles_files 
      

      然后,当您拥有需要修改的文件的所有路径时:

      for the_path in list_path_styles_files:
              for line in fileinput.input(the_path, inplace=1):
                      line = line.replace('font-size=15','font-size=12')
                      line = ...
                      ...
                      print line 
      

      这会一一读取行,然后按照你想要的方式修改行,然后放到文件中

      【讨论】:

        猜你喜欢
        • 2011-12-13
        • 1970-01-01
        • 2011-04-08
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 2011-02-15
        • 1970-01-01
        • 2015-07-17
        相关资源
        最近更新 更多