python - 使用 python 注释文本文件中的某些行

标签 python scripting

我是 python 的新手,我刚刚开始学习基础知识。

我正在尝试创建一个程序,它将获取一个文件并注释(使用 # )等号后没有任何内容的行。

例如,

V12 =

V13 = 3

应该是

#V12 =

V13 = 3

预先感谢您的帮助。

最佳答案

基本上,您需要读入文件。然后,检查每一行。如果在等号上拆分后该行有内容,则按原样输出该行;否则,在前面附加一个标签,然后输出该行。

f = open(filename, "r")
lines = f.readlines()
f.close()

output_lines = []
for line in lines:
    if len(line.split("=")[1]) > 0:
       output_lines.append(line)
    else:
       output_lines.append("#" + line)
f = open("commented" + filename, "w")
f.write("\n".join(output_lines))
f.close()

关于python - 使用 python 注释文本文件中的某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381030/

相关文章:

perl - 计算图中子图的出现次数

html - 检查 file.html 是否存在的脚本,如果存在,则运行另一个脚本,否则会死吗?

linux - Bash 脚本 : bad interpreter

python - 如何访问 Pandas 数据透视表的索引列

python - 导入错误 : No module named 'cryptography'

python tesseract 结果在句子之间给出了不必要的额外行间隙

python - 从 difflib 中获取更细粒度的差异(或者通过后处理差异来实现相同目的的方法)

linux - 从匹配多个模式的一个文件创建新的多个文件的快速方法

windows - 批处理脚本、Powershell 和不触发 Windows 中的 UAC

python - 如何在模型中设置元类中未定义的字段