import os def is_file_empty(file_path): try: with open(file_path, 'r', encoding='utf-8') as file: return not file.read().strip() except FileNotFoundError: # 如果文件不存在,可以视为“空”或抛出异常,这里选择返回True return True if __name__ == '__main__': # txt_path = '/home/admin-root/haotian/python哈汽安全帽识别/fire_smoke/train/labels' txt_path = '/home/admin-root/haotian/python哈汽安全帽识别/fire_smoke/val/labels' # save_path = 'fire_smoke/remove/train.txt' save_path = 'fire_smoke/remove/val.txt' all_txt_path = [os.path.join(txt_path, t) for t in os.listdir(txt_path)] for txt in all_txt_path: if is_file_empty(txt): with open(save_path, 'a') as f: f.writelines(txt+'\n') # print(txt)