python常用处理脚本

1、读写文件

with open("1.txt", "r") as f:
    lines = f.readlines()
    lines.sort()

with open("2.txt", "w") as fw:
    for i in range(len(lines)):
        file = lines[i]
        # file = lines[i].rstrip() # 去掉空格
        fw.write(file)
fw.close()

2、读取文件列表

input_file_path = "/home/data"
files = os.listdir(input_file_path) # 子文件中的文件列表
files.sort()
print(len(files))
for i in range(len(files)):
    file = files[i]
    file_path = "{}/{}".format(input_file_path, file)

3、文件重命名

import os
os.rename(src_file, dst_file)

4、打印输出设置固定长度

  • 例如:000001.wav
save_file = './save_vad/{:0>6d}.wav'.format(index)

5、复制文件

import shutil
shutil.copy(src_path,  dst_path)

6、获取文件后缀名

filename = os.path.basename(file_path)
(filename_shotname, filename_extension) = os.path.splitext(filename)

7、判断是否存在该路径,不存在则创建文件

if not os.path.exists(save_path):
	os.makedirs(save_path)

8、判断是否存在该路径,存在则删除文件

if os.path.exists(tfrecord_file):
    os.remove(tfrecord_file) # 删除文件
    os.makedirs(tfrecord_file) # 删除目录

9、读取文件列表,将文件路径存入txt

import os 
input_path = "./example"
list_file = os.listdir(input_path)
all_lines = []

for i in range(len(list_file)):
    file_name = list_file[i]
    src_path = "{}/{}".format(input_path, file_name)
    sv_line = "{}\n".format(src_path)
    all_lines.append(sv_line)

with open("./example.txt", "w") as fw:
    fw.writelines(all_lines)
    fw.close()

10、导入上级目录模块或文件

import sys
sys.path.insert(0, "moulde_path")

猜你喜欢

转载自blog.csdn.net/wjinjie/article/details/127753126