读写文本文件并添加行号(python程序设计实验25)

读写文本文件并添加行号

filename = 'demo.py'
lst1 = ['0\n' for i in range(100)]
lst2 = [str(i)+'\n' for i in range(100)]

with open(filename, 'w') as fp:
    fp.writelines(lst1)
    fp.writelines(lst2)
fp.close()

with open(filename, 'r') as fp:
    lines = fp.readlines()
maxLength = len(max(lines, key=len))
fp.close()

lines = [line.rstrip().ljust(maxLength)+'#'+str(index)+'\n' for index, line in enumerate(lines)]
with open(filename[:-3]+'_new.py', 'w') as fp:
    fp.writelines(lines)
fp.close()

你可能感兴趣的:(实验,python)