首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python文件常用操作

python文件常用操作

作者头像
bear_fish
发布2018-09-14 10:04:42
5110
发布2018-09-14 10:04:42
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338383

python (glob os.path)常用文件操作:

  • python excel 操作
  • python批量重命名目录下(单个或者多个)文件
  • 目录以及文件名的一些操作(获取文件名不要扩展名without extension)
  • text 文件的读取

例如:

前面测试图片识别的时候需要将测试结果写到excel中

像这样批量重命名文件的话在linux中有很多常用的命令具体看我的bolg

直接上代码了

# _*_ coding:utf-8 _*_
from os import listdir
from os.path import isfile, join
import glob
import os
import errno
from xlwt import *
import time

def make_dir_not_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise


def get_line_lst(filename):
    """
    return list of every line in file
    :param filename the file to be readed
        like '../dataset/dataset.txt':
    :return like [['line1 1'], ['line2 2']]:
    """
    lst = []
    with open(filename) as fp:
        for line in fp:
            lst.append(line)

    return lst


def write_list_excel(file_name, title_lst, row_lst):
    # excel operator handler
    excel_handler = Workbook(encoding='utf-8')
    excel_sheet_name = time.strftime('%Y-%m-%d')
    excel_sheet = excel_handler.add_sheet(excel_sheet_name)

    # write title
    col_idx = 0
    for item in title_lst:
        excel_sheet.write(0, col_idx, item)
        col_idx += 1

    # write row contents, index->row
    row_idx = 1
    for row in row_lst:
        col_idx = 0
        for item in row:
            excel_sheet.write(row_idx, col_idx, item)
            col_idx += 1
        row_idx += 1

    # write/save excel to file
    excel_handler.save(file_name)


def test_write_list_excel():
    file = 'F:/test.xlsx'
    title_lst = ['姓名', '性别', '年龄', ]
    row_lst = [['熊大', '男', 10], ['熊2', '男', '15'], ['强哥', '男', 25]]
    write_list_excel(file, title_lst, row_lst)

def batch_rename_files_in_dir():
    """
    signal level dir
    :return:
    """
    base_dir = 'F:/ad_samples/img_voice_test/tencent_img/violence_samples/'
    file_list = glob.glob(base_dir + "*.jpg")
    i = 0
    for f in file_list:
        os.rename(f, os.path.join(base_dir, str(i) + '.jpg'))
        i += 1

def batch_rename():
    """
    two-level dir
    added 2017/8/17, rename dir hello.jpg
    :return:
    """
    # base_dir = 'F:/ad_samples/test_samples/'
    sub_dir_list = glob.glob(base_dir + '*')
    # print sub_dir_list ['F:/dir1', 'F:/dir2']
    for dir_item in sub_dir_list:
        files = glob.glob(dir_item + '/*.jpg')
        i = 0
        if len(files) == 0:
            continue
        for f in files:
            # fname = 'xx' + str(i)
            os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
            i += 1

def get_file_name():
    file_path = 'E:/img/10.jpg'
    print os.path.basename(file_path)
    # 10.jpg

    head, tail = os.path.split(file_path)
    print head, tail
    # E:/img 10.jpg

    print os.path.splitext(file_path)
    # ('E:/img/10', '.jpg')
    print os.path.splitext(file_path)[0]
    # E:/img/10

    base = os.path.basename(file_path)
    # 10.jpg
    print os.path.splitext(base)
    # ('10', '.jpg')
    print os.path.splitext(base)[0]
    # 10

def all_subdir_join():
    """
    more details of sub dir search visits
    https://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
    :return:
    """
    base_dir = 'F:/ad_samples/train_samples/others/'
    sub_dir_lst = glob.glob(base_dir + "*")
    # ['F:/dir1', 'F:/dir2']
    new_sub_dir = [os.path.join(base_dir, item + '_flip') for item in os.listdir(base_dir)]
    # ['F:/dir1_flip', 'F:/dir2_flip']
    # find all the .c files in the dir of src
    glob.glob(os.path.join('src', '*.c'))

    # find all the .c files in the one level subdir of src
    glob.glob(os.path.join('src', '*', '*.c'))
    # print os.listdir(base_dir)
    # ['dir1', 'dir2']
    # print glob.glob(base_dir + "*")
    # ['F:/dir1', 'F:/dir2']

def get_all_files_name_in_dir(dir):
    files = [f for f in listdir(dir)]
    # like ['1.jpg', '10.jpg', '2.jpg', 'dir']

    files = [f for f in listdir(dir) if isfile(join(dir, f))]
    # doesn't contain directory
    # like ['1.jpg', '10.jpg', '2.jpg']
    files = [join(dir, f) for f in listdir(dir) if isfile(join(dir, f))]
    # like ['E:/img\\1.jpg', 'E:/img\\10.jpg', 'E:/img\\2.jpg']

    files = [f for f in listdir(dir) if f.endswith('.jpg')]
    # like ['1.jpg', '10.jpg', '2.jpg']

    files = glob.glob(dir + '/*.jpg')
    # like ['E:/img\\1.jpg', 'E:/img\\10.jpg', 'E:/img\\2.jpg']
    os.chdir(dir)
    files = glob.glob('*.jpg')
    # like ['1.jpg', '10.jpg', '2.jpg']
    return files

if __name__ == '__main__':
    # batch_rename()
    batch_rename_files_in_dir()
    test_write_list_excel()
    # get_file_name()
    # print get_all_files_name_in_dir('E:/rectimg')
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年08月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档