with open('in.txt', 'a') as outfile:
with open('test.txt', 'r') as infile:
for line in infile.readlines():
if line.startswith('abc'):
outfile.write(line.strip() + " # Here's abc\n")
else:
outfile.write(line)
wfile = open("commentFile.py","r+")
d = wfile.readlines()
wfile.seek(0)
allLines = []
for line in d:
if("comment" in line and "#" not in line):
allLines.append("#"+line)
else:
allLines.append(line)
wfile.writelines(allLines)
wfile.close()
不如一行一行地读入文件,然后根据您的需要,在输出文件中附加行注释或不注释。你知道吗
例如,要在以字符串
abc
开头的每一行添加注释,可以执行以下操作:这将使:
从输入文件:
检查一行是否需要注释也可以通过regex搜索,或者通过修改我的示例,您也可以注释某些行号。但这取决于你自己。你知道吗
下面是一个python解决方案,它接受一个名为
commentFile.py
的文件,并注释掉任何包含字符串comment
的行。你知道吗是的。你可以打开一个文件,逐行读取
将特定行作为原始字符串或带有if条件的正则表达式进行搜索,并将其替换为
写入相同的文件,如:
这有什么难的?你知道吗
相关问题 更多 >
编程相关推荐