在使用python的过程中,经常会对文件进行读写操作,本文主要介绍几个简单的文件操作,基于python的os库实现。
遍历文件夹下某种类型的文件
def read_alover_dir(trg_dir):
file_list = []
file_type = '.jpg'
for filename in trg_dir:
if filename.endwith(file_type):
file_list.append(filename)
file_list.sort()
写入txt文件
def write_txt(file, content):
f = open(file, 'w')
f.writelines(content)
f.close()
合并多个txt文件的内容
def merge_txt(filepath_list, trg_file):
f = open(trg_file, 'w')
for filepath in filepath_list:
for line in open(filepath, encoding="utf-8"):
f.writelines(line)
f.close()
判断文件夹是否存在,并创建文件夹
trg_dir = './datasets/car'
if not os.path.exists(trg_dir):
os.makedirs(trg_dir)
感谢阅读,如果对您有帮助,希望点个赞!