当前位置: 代码迷 >> 综合 >> utils系列:python 移动、保存文件,list、dict 转txt 、csv、excel ,txt,excel转list等等代码
  详细解决方案

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

热度:21   发布时间:2023-12-15 00:33:13.0

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)lllist.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.nrowscol_Num = table.ncolss =[]key =table.row_values(0)# 这是第一行数据,作为字典的key值if row_Num <= 1:print("没数据")else:j = 1for 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)

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

  相关解决方案