我的这部分代码(应该从其他Python脚本中删除python2style注释)没有任何作用。为什么?

2024-06-10 07:23:01 发布

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

这只有30行,所以我会把整件事都贴出来。整个脚本应该获取另一个.py文件并重写它,使其完全位于一行。我遇到的一个问题是,如果脚本有任何注释,它会每隔一行注释掉一行。不起作用的部分用#*注释这是不起作用的部分*该部分要做的是删除#字符和该行后面的所有内容,但它似乎什么都没做。你知道吗

from sys import argv

script, input_file = argv

def make_one_line(f):
    # reads the file, then adds each line to a list
    # then adds that line to 'final'
    one_line = ''
    text_body = f.read()
    f.seek(0)
    lines = text_body.splitlines()
    lines.reverse() # this is done because pop() starts at the back
    # ****THIS IS THE PART THAT DOESN'T WORK****
    for line in lines:
        line.split("#")
    # ****THIS IS THE PART THAT DOESN'T WORK****
    while lines != []:
        next_one = lines.pop()
        one_line += next_one
        one_line += ';'
    return one_line


print "This will rewrite the file, press CTRL-C to cancel."
raw_input('Press any key (but CTRL-C) to continue.')

current_file = open(input_file, 'r+')
final = make_one_line(current_file)
current_file.truncate()
current_file.seek(0) # if this isn't here, you get an error on Windows
current_file.write(final)

Tags: thetotext脚本inputmakelinecurrent
3条回答

你知道吗结构拆分返回拆分元素的函数。它不修改参数,因为字符串是不可变的。您也不能用for循环写入正在迭代的列表。相反,请考虑:

uncommented_lines = []
for line in lines:
    uncommented_lines.append(line.split('#')[0])

这可以用更少的代码和更高效的方式实现您想要的:

import fileinput

print ';'.join(line.strip('\n ').split('#')[0] for line in fileinput.input())

要测试,请将此代码放入make_one_line.py,然后执行以下操作:

python make_one_line.py other.py

基于@Steve的回答,他指出字符串是不变的。还有什么理由使用read()splitlines()reverse()pop()?这不管用吗:

def make_one_line(f):
    uncommented_lines = (line.rstrip('\n').split('#')[0] for line in f) 
    return ';'.join(uncommented_lines)

相关问题 更多 >