python获取文件路径、文件夹内所有文件

python获取文件路径、文件夹内所有文件名字

项目内相对路径 在test12.py内 想获取其所在文件夹的所有的表格文件 windows

第一种方案

"""获取路径"""
def list_dir(file_dir):

    通过 listdir 得到的是仅当前路径下的文件名,不包括子目录中的文件,如果需要得到所有文件需要递归

print(

<><><><><><> listdir <><><><><><>)
print ("current dir : {0}".format(file_dir))
dir_list = os.listdir(file_dir)
for cur_file in dir_list:
    # 获取文件的绝对路径
    path = os.path.join(file_dir, cur_file)
    # if os.path.isfile(path): # 判断是否是文件还是目录需要用绝对路径
        # print ("{0} : is file!".format(cur_file))
    print(cur_file)
    # if os.path.isdir(path):
        # print("{0} : is dir!".format(cur_file))
        # list_dir(path) # 递归子目录


# path=rC:\UserswenDesktoppisx_gitB2020931-PX-GWC-Services
dsystemjiaobenk
path=r..k
list_dir(path)
# os.listdir(path)

第二种方案

"""获取文件夹下的所有文件"""

for f_path, dir_name, f_names in os.walk(r../bk):
print(f_path)
print(dir_name)
print(f_names)

Linux

#获取路径
dirinfo = rdsystem/jiaoben/bk/
#生成文件
filenames = str(uuid.uuid1()) + .docx

扩展: 1.生成word文件并生成数据流返给前端

dirinfo = graphsystem/files/
filenames = str(uuid.uuid1()) + .docx
resume_path = dirinfo + filenames
# resume_path = dirinfo + %s.docx % info[1]
document.save(resume_path)
file = open(resume_path, mode=rb)
response = FileResponse(file)
response[Content-Type] = application/octet-stream
response[Content-Disposition] = attachment;filename=down_resume.docx
os.remove(resume_path)
return response

2.word转pdf文件生成数据流返给前端

Wpx2Pdf.all2pdf(resume_path, dirinfo)
pdfile1 = filenames.replace(os.path.splitext(filenames)[-1], .pdf)
pdf_file = dirinfo + pdfile1
if os.path.exists(dirinfo + pdfile1):
    file = open(pdf_file, mode=rb)
    response = FileResponse(file)
    response[Content-Type] = application/octet-stream
    response[Content-Disposition] = attachment;filename=down_resume.pdf
    os.remove(pdf_file)
    os.remove(resume_path)
    return response

Wpx2Pdf源码:

经验分享 程序员 微信小程序 职场和发展