Python - 删除 Python 代码中的注释

Python - Delete comments in a Python code

所以我必须编写一个代码来删除 Python 代码中的每个 # 注释... 我写了一个代码(文件方法)但是它删除了所有东西...... 任何帮助都将是 appreciated.Thanks.

我的代码:

code=open("comm.txt","r")
for line in code:
if (line.startswith("#")):
    del line
code.close()

您不能修改用 'r' 打开以供阅读的文件。此外,您不应该在遍历它时修改可迭代对象

with open('comm.txt', 'r') as code, open('comm_edit.txt', 'w') as out:
    for line in code:
        if not line.startswith('#'):
            out.write(line + '\n')

这将打开第二个文件进行写入,并写出任何不以 '#' 开头的行。请注意,您忽略了一些人在代码旁边添加注释的事实

x = 5   # like this

这样试试:

code = open("comm.txt","r")
code_back = open("new_comm.txt","w")
for line in code:
    if not line.startswith("#"):  #you dont need bracket here
        code_back.write(line)

code.close()
code_back.close()