通过 25 行脚本运行它后,它只将前 20 行变成了一行。该脚本还删除了注释,它也仅在前 20 行中删除了注释。为什么它忽略最后五行?
from sys import argv
script, input_file = argv
def make_one_line(f):
uncommented_lines = (line.rstrip('\n').split('#')[0] for line in f)
return ';'.join(uncommented_lines)
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)
这是我测试过的脚本:
from sys import argv
script, input_file = argv
def reverse_file(f):
# reads the file, then adds each character to a list,
# then reverses them
final = ''
text_body = f.read()
chars = list(text_body)
chars.reverse()
# this puts the characters from the list into a string
for i in chars:
final += i
return final
print "This will rewrite the file, press CTRL-C to cancel."
print "(Although you can undo the damage by just running this again.)"
raw_input('Press any key (but CTRL-C) to continue.')
current_file = open(input_file, 'r+')
final = reverse_file(current_file)
current_file.truncate()
current_file.seek(0) # if this isn't here, you get an error on Windows
current_file.write(final)