utils系列:python 移动、保存文件,list、dict 转txt 、csv、excel ,txt,excel转list等等代码

txt转list

def readfiel(path):
    # path = "E:/data/txt/"
    list1 = []
    flielist = os.listdir(path)
    for f in flielist:
        list = []
        filename= ["filename"]
        # f =os.path.join(path,f)ll
        list.append(f)
        dic = dict(zip(filename,list))
        list1.append(dic)
    return(list1)


#读取TXT文件为list
def TXT(path):
    result=[]
    list1 = []
    with open(path,'r') as f:
        for line in f:
            print(line)
            result.append(list(line.strip('\n').split(',')))
    list1 = split(result)
        # print(list1)
    return list1

excel转list

#将多层列表转为单层列表
def split(li:list, new_list=[]):
    for ele in li:
        if isinstance(ele, list):
            split(ele)
        else:
            new_list.append(ele)
    return new_list

#excel 读取列转为列表
def excel_one_line_to_list(path):
    df = pd.read_excel(path,usecols=[0])  # 读取列
    df_li = df.values.tolist()
    list = split(df_li)
    return list

list按行写入txt

#将list按行写入txt文件
def writelisttotxt(list,path):
    with open(path,'a',encoding='utf-8') as f:
        for i in list:
            f.write(i+"\n")
        return 0

dict写入txt

#字典写入txt文件
def wirte_txt(dic,txt_path):
    with open(txt_path,'a',encoding = 'utf-8') as f1 :
        f1.write(str(dic)+"\n")
    return 0

写入excel

def read_excel(path):
    #打开excel表,填写路径
    book = xlrd.open_workbook(path)
    #找到sheet页
    table = book.sheet_by_name("sheet1")
    #获取总行数总列数
    row_Num = table.nrows
    col_Num = table.ncols

    s =[]
    key =table.row_values(0)# 这是第一行数据,作为字典的key值

    if row_Num <= 1:
        print("没数据")
    else:
        j = 1
        for i in range(row_Num-1):
            d ={}
            values = table.row_values(j)
            for x in range(col_Num):
                # 把key值对应的value赋值给key,每行循环
                d[key[x]]=values[x]
            j+=1
            # 把字典加到列表中
            s.append(d)
        return s

保存csv文件

#保存CSV文件
def save_csv(list):
    df = pd.DataFrame(list)
    path = './normal.csv'
    df.to_csv(path, encoding= 'utf_8_sig')
    return 0

遍历文件夹

#遍历文件夹
def iter_files(rootDir,file):
    #遍历根目录
    for root,dirs,files in os.walk(rootDir):
        # for file in files:
        #     file_name = os.path.join(root,file)
        #     print(file_name)
        if file in files:
            file_name = os.path.join(root,file)
    return file_name

移动文件

#移动文件到另一个文件
def move(old_path,new_path,filename):
    src = os.path.join(old_path, filename)
    dst = os.path.join(new_path, filename)
    print('src:', src)
    print('dst:', dst)
    shutil.move(src, dst)

有更好方法的大佬欢迎点评

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值