import sys
import os
def create_file(filename,num):
count = 0
dest_file='{}.bak'.format(filename)
with open(filename, mode='r', encoding='utf-8') as f_r:
for line in f_r:
count += 1
count -= int(num)
start = 0
with open(filename, mode='r', encoding='utf-8') as f_r, open(dest_file, mode='w',
encoding='utf-8') as f_w:
for line in f_r:
start += 1
if start > count:
f_w.write(line)
os.remove(filename)
os.rename(dest_file,filename)
if __name__ == '__main__':
create_file(sys.argv[1],sys.argv[2])
语法:
python3 xxx.py filename num
例子:
python3 file_clean.py 5000