我的单行重写器只重写脚本的一部分

时间:2013-09-07 07:44:35

标签: python python-2.7

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

1 个答案:

答案 0 :(得分: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()