Python:如何打开文件并注释特定行?

2024-04-25 03:49:56 发布

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

有没有办法打开一个文件(比如一个.py文件)并注释文件中已经存在的某一行? 或者有没有办法创建一段代码,用另一行代码替换这一行?你知道吗


Tags: 文件代码py办法
3条回答

不如一行一行地读入文件,然后根据您的需要,在输出文件中附加行注释或不注释。你知道吗

例如,要在以字符串abc开头的每一行添加注释,可以执行以下操作:

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)

这将使:

abc 1 # Here's abc
blabla 2
def 3
abc 4 # Here's abc

从输入文件:

abc 1
blabla 2
def 3
abc 4

检查一行是否需要注释也可以通过regex搜索,或者通过修改我的示例,您也可以注释某些行号。但这取决于你自己。你知道吗

下面是一个python解决方案,它接受一个名为commentFile.py的文件,并注释掉任何包含字符串comment的行。你知道吗

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()

是的。你可以打开一个文件,逐行读取

with open('file.py') as f:
    lines = f.readlines()

将特定行作为原始字符串或带有if条件的正则表达式进行搜索,并将其替换为

for n, line in enumerate(lines):
    if(line == search_line):
        lines[n] = new_line

写入相同的文件,如:

with open('file.py', 'w') as f:
    f.write(''.join(lines))

这有什么难的?你知道吗

相关问题 更多 >