0

通过 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)
4

1 回答 1

1

由于混合换行符类型,您可能会遇到问题:试试这个:

from sys import argv

script, input_file = argv

def make_one_line(f):
    uncommented_lines = (line.rstrip('\n\r').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, 'rU') # Open in universal newline mode
final = make_one_line(current_file)
current_file.close()
outfile = open("out_"+input_file, "wt") # Save the output in a new file
outfile.write(final)
outfile.write('\n')
outfile.close()
于 2013-09-07T09:03:04.880 回答