これを 25 行のスクリプトで実行すると、最初の 20 行だけが 1 行になりました。このスクリプトはコメントも削除しますが、これも最初の 20 行でのみ行われます。最後の 5 行を無視するのはなぜですか?
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)