记录贴
要用python写一个删除文件夹内所有txt文件中每行的末尾字符。如下所示,即删去末尾的字符‘0’及其前面的空格。
937 913 921 912 923 874 940 875 ship 0
638 959 638 935 694 939 693 962 ship 0
545 494 548 518 489 519 488 493 ship 0
代码如下:
import os
def delete_num(srcpath, outpath):
filelist = os.listdir(srcpath)
os.makedirs(outpath)
for file in filelist:
f = open(srcpath + '/' + file)
src_name = file.split('.')[0]
dst_name = src_name + '.txt'
outfile = open(outpath + '/' + dst_name, 'w')
for line in f.readlines():
line = line[:-2]
line = line.rstrip()
outfile.write(line+'\n')
f.close()
outfile.close()
if __name__ == '__main__':
delete_num('E:\labelTxt_num', 'E:\labelTxt') # 分别为源路径和处理后的新路径