打开文件夹,选择路径
import tkinter as tk
from tkinter import filedialog
"""打开文件夹,获取文件夹路径"""
def open_file():
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()
print('\n获取的文件夹地址 %s' %path)
return path
循环遍历文件夹中的文件
import os
path ='路径'
filelist = [] #文件列表
for file in os.listdir(path):
filename,extname = os.path.splitext(file)
"""
file: 文件名 test.txt
filename: 文件名前缀 test
extname:文件名后缀 .txt
"""
filelist.append(file)
进阶-遍历改路径下的所有文件(递归)
import os
path = '路径'
pathbak = path #设置根目录路径
filenamelist = [] #定义
def read(path):
for file in os.listdir(path):
pathname = os.path.join(path,file)
#判断改路径指定的是文件夹还是路径
if os.path.isdir(pathname):
#如果是文件,递归调用函数
read(pathname)
else:
#如果是文件,则加入list中
#去掉根目录路径,或得文件相对路径
print(pathname.replace(pathbak,''))
filenamelist.append(pathname.replace(pathbak,''))
重命名文件
import os
#oldname 文件旧名称
#newname 文件新名称
#path 文件所在路径
def renamefile(oldname,newname,path):
oldfilepath = os.path.join(path,oldname) #旧名称
newfilepath = os.path.join(path,newname) #新文件
#重命名
os.rename(oldfilepath,newfilepath)
复制文件到指定路径
import os
import shutil
"""
复制文件到指定路径 srcpath 文件所在文件夹路径,dist 目的文件夹路径 filename 文件名称
"""
def copyVersionFile(srcpath,distpath,filename):
#文件所在路径文件
srcFilePath = os.path.join(srcpath,filename)
#目的路径文件
dstFilePath = os.path.join(dispath,filename)
#如果该路径不存在,则创建文件夹
if not os.path.exists(distpath):
os.makedirs(distpath)
#如果源文件存在,则开始复制
if os.path.exists(srcFilePath):
shutil.copyfile(srcFilePath,dstFilePath)
读取excel文件
import pandas as pd
#读取excel表格转为DataFrame
#sheet_name 为指定工作簿,可以用 索引 0 表示指定第一个工作簿,也可以用 'sheet1' 指定
#header None 表示不带第一行
#usecolds="A,D,K" 表示取 A,D,K列数据
df = pd.read_excel(r'D:\Desktop\测试\表格.xlsx',sheet_name=0,header=None,usecols="A,D,K")
#删除指定行列
""" drop()函数用于删除指定行、列,同时可以删除多行,多列"""
df.drop(labels=2,axis=0,inplace=True)
#删除含有NaN值的所有行
#默认 axis=0
df.dropna(how="any",inplace=True)