简体   繁体   中英

full file path for zipped folder in python

I have the following code that is trying to get the full file path (including the folder):

import zipfile
import os
import sys

zipped_files_dir = 'Z:\Dev\some_files'

def get_folder_names():
    path_list = []
    for folder_name in os.listdir(zipped_files_dir):
        path_list.append(folder_name)
    return path_list

def get_folder_directories(folder_list):
    for folder in folder_list:
        pathname = os.path.abspath(folder)
        print(pathname)

def main():
    get_folder_directories(get_folder_names())

>>>Z:\Dev\new_folder.zip  

My problem is that I should have "\\some_files\\new_folder.zip" in the returned directory. Any ideas?

Thanks!

You could use os.path.join(zipped_files_dir, folder) in the get_folder_directories function:

import zipfile
import os
import sys

zipped_files_dir = 'Z:\Dev\some_files'

def get_folder_names():
    path_list = []
    for folder_name in os.listdir(zipped_files_dir):
        path_list.append(folder_name)
    return path_list

def get_folder_directories(folder_list):
    for folder in folder_list:
        pathname = os.path.abspath(os.path.join(zipped_files_dir, folder))
        print(pathname)

def main():
    get_folder_directories(get_folder_names())

Or, path_list.append(os.path.join(zipped_files_dir, folder_name)) in get_folder_names() :

import zipfile
import os
import sys

zipped_files_dir = 'Z:\Dev\some_files'

def get_folder_names():
    path_list = []
    for folder_name in os.listdir(zipped_files_dir):
        path_list.append(os.path.join(zipped_files_dir, folder_name))
    return path_list

def get_folder_directories(folder_list):
    for folder in folder_list:
        pathname = os.path.abspath(folder)
        print(pathname)

def main():
    get_folder_directories(get_folder_names())

Chown has the correct solution.

In your code you pass abs_path the string "new_folder.zip". But abs_path doesn't know where it came from, so it figure it must be in the current working directory which is why you get r"Z:\\Dev\\new_folder.zip". You need to use os.path.join to combine the filename with the path you find it in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM