这只有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)
你知道吗结构拆分返回拆分元素的函数。它不修改参数,因为字符串是不可变的。您也不能用for循环写入正在迭代的列表。相反,请考虑:
这可以用更少的代码和更高效的方式实现您想要的:
要测试,请将此代码放入
make_one_line.py
,然后执行以下操作:基于@Steve的回答,他指出字符串是不变的。还有什么理由使用
read()
、splitlines()
、reverse()
和pop()
?这不管用吗:相关问题 更多 >
编程相关推荐