相信大家用Git进行版本控制都会为.gitignore 文件发过愁吧,像我就去GitHub官方的库https://github.com/github/gitignore去下载.可这就出现一个问题,比如,我按照我的需求,对应将Python,Vim,JetBrains,C和C++的内容筛选后复制到我的.gitignore 文件里,这时我的.gitignore 文件已经有将近900行,有不少注释,空行,以及一些重复的内容,真是让强迫症无语,还平白增加仓库体积,于是就写了个简单的程序来应对(封装成类主要是为了有其他相同需求的文件使用此程序时更方便些).
class Cleaner:
def __init__(self, filename):
self.filename = filename
def clean(self):
with open(self.filename, "r", encoding="utf-8") as f:
seen = set()
result = []
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if line not in seen:
result.append(line)
seen.add(line)
with open(self.filename, "w", encoding="utf-8") as f:
for line in result:
f.write(line + "\n")
# 调用示例
# cleaner = Cleaner(".gitignore")
# cleaner.clean()
|