如何查找和替换字符编码?

2024-10-03 00:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我们软件的版权声明需要提前到2014年。这意味着:

  1. 打开每个名为AssemblyInfo.cs的文件(在工作目录中或其下)
  2. 将任何包含“AssemblyCopyright”的行替换为下面的整行。你知道吗

[assembly: AssemblyCopyright("Copyright © 2014 Company")]

听起来是个完美的自动化小任务。我写了一个python3脚本,但是它考虑了版权标志。我想这是由于字符编码问题。你知道吗

那么,如何进行编码查找和替换呢?更改版权行而不更改文件编码。你知道吗

我不可靠的脚本是Python,但只要能正常工作,我不介意使用另一种语言(C#、Ruby、Nodejs等等)。你知道吗


出于好奇,这是我的Python脚本。你知道吗

#!python
import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk('.'):
  for filename in filenames:
    if filename != 'AssemblyInfo.cs':
        continue
    path = os.path.join(root, filename)

    with open(path) as f:
        lines = list(f)

    new_lines = list()
    changed = False

    for line in lines:
        if "AssemblyCopyright" in line:
            line = '[assembly: AssemblyCopyright("Copyright © 2014 Company")]\r\n'
            changed = True

        new_lines.append(line)

    if not changed:
        continue

    print(path)

    with open(path, 'w') as f:
        f.write("".join(new_lines))

Tags: pathin脚本编码newforifos