Python Forum
Downloading And Saving Zip Files To A Particular Path Folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Downloading And Saving Zip Files To A Particular Path Folder
#1
Hi there,

How would I alter the following Code, so that when the .Zip Files are downloading, they are saved to a Particular Specified Folder on my Computer, depending on, a specific part of text, they have in the .Zip Filename ?

For example, say I wanted all .Zip Files, which had 737-400 in the Filename or 737-800, saved to :-

C:\Users\Edward\PAI Aircraft\Boeing\B737-400

And

C:\Users\Edward\PAI Aircraft\Boeing\B737-800

Respectively

All .Zip Files which had 320-200 in the Filename, saved to :-

C:\Users\Edward\PAI Aircraft\Airbus\A320-200

All .Zip Files which had 195-200 in the Filename, saved to :-

C:\Users\Edward\PAI Aircraft\Embraer\E195-200

All .Zip Files that didn't fit, into a particular specified Category, saved to :-

C:\Users\Edward\PAI Aircraft\Misc

etc etc.

This is the last bit, of the Python Code I have :-

def download(all_planes):
    '''Download zip for 1 plain,feed with more url download all planes'''
    # A_300 = next(all_planes())  # Test with first link
    how_many_planes = islice(all_planes(), 0, 10)
    for plane_url in how_many_planes:
        url_get = requests.get(plane_url)
        soup = BeautifulSoup(url_get.content, 'lxml')
        td = soup.find_all('td', class_="text", colspan="2")
        zip_url = 'http://web.archive.org/web/20041108022719/http://www.projectai.com:80/libraries/download.php?fileid={}'
        for item in tqdm(td):
            zip_name = item.text
            zip_number = item.find('a').get('href').split('=')[-1]
            with open(zip_name, 'wb')  as f_out:
                down_url = requests.get(zip_url.format(zip_number))
                f_out.write(down_url.content)
  
if __name__ == '__main__':
    download(all_planes)
Any help would be appreciated

P.S. Is that part of the Python Code I posted, sufficient for people, to help me, with answering my question ?
Or do I need to post, the Full Python Code ?

Regards

Eddie Winch
Reply
#2
The following code will return a path where to place file, based of file name.
will work with all file suffixes as written, searches filename stem for aircraft type.

Automatically creates directory if it doesn't already exist.
Won't harm existing directories.

change homepath to your base directory, for your code should, this should be (I can't test on windows as I don't use it):
homepath = Path("C:/Users/Edward")
to add new aircraft (and auto create directories) add entry to 'self.aircraft_type' dictionary.
The first time that aircraft type is encountered in a filename, it will create the new directory.

Example program TryAircraftPaths.py shows how to use the AircraftPaths class
As written, homepath will be in source code directory as 'All_My_Aircraft', this can be changed as required.

So in your program:
add two lines:
import AircraftPaths

and instantiate class:
ap = AircraftPaths.AircraftPaths()
then:
ap.get_aircraft_path(zipname)
will return save path

AircraftPaths.py:
from pathlib import Path
import os


class AircraftPaths:
    def __init__(self):
        # Assures starting directory is source
        os.chdir(os.path.abspath(os.path.dirname(__file__)))

        # Set this equal to you're base path (top level where 
        homepath = Path('.')

        self.basepath = homepath / 'All_My_Aircraft'
        self.basepath.mkdir(exist_ok=True)

        self.aircraft_type = {
            '737-400': {
                'subpath': 'Boeing',
                'aircraft': 'B737-400'
            },
            '737-800': {
                'subpath': 'Boeing',
                'aircraft': 'B737-800'
            },
            '320-200': {
                'subpath': 'Airbus',
                'aircraft': 'A320-200'
            },
            '195-200': {
                'subpath': 'Embraer',
                'aircraft': 'E195-200'
            },
            'general': {
                'subpath': 'PAI Aircraft',
                'aircraft': 'Misc'
            }
        }

    def get_aircraft_path(self, zipfilename):
        for code, details in self.aircraft_type.items():
            if code in zipfilename:
                ap = self.basepath / f"{details['subpath']}"
                ap.mkdir(exist_ok = True)

                airpath = ap / f"{details['aircraft']}"
                airpath.mkdir(exist_ok = True)
                return airpath

        ap =  self.basepath / f"{self.aircraft_type['general']['subpath']}"
        ap.mkdir(exist_ok = True)
        airpath = ap / f"{self.aircraft_type['general']['aircraft']}"
        airpath.mkdir(exist_ok = True)
        return airpath
    
if __name__ == '__main__':
    ap = AircraftPaths()
    print(ap.aircraft_type)
TryAircraftPaths.py
import AircraftPaths


def main():
    ap = AircraftPaths.AircraftPaths()

    zipfilelist = [
        "ziggy195-200theMonster.zip",
        "Caltech320-200hacked.zip",
        "UnknownAircraft.zip",
    ]

    for zipname in zipfilelist:
        path = ap.get_aircraft_path(zipname)
        print(f"Path to save file in is: {path.resolve()}")

if __name__ == '__main__':
    main()
running test program TryAircraftPaths will display (set your homepath in AircraftPaths.py before running):
Output:
Path to save file in is: .../projects/T-Z/T/TryStuff/src/Paths/All_My_Aircraft/Embraer/E195-200 Path to save file in is: .../projects/T-Z/T/TryStuff/src/Paths/All_My_Aircraft/Airbus/A320-200 Path to save file in is: .../projects/T-Z/T/TryStuff/src/Paths/All_My_Aircraft/PAI Aircraft/Misc
Reply
#3
Thankyou so much Larz60+, your help is very much appreciated.
I can't wait to try, what you say to do out ! Smile

Regards

Eddie Winch
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create dual folder on different path/drive based on the date agmoraojr 2 431 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 530 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Rename files in a folder named using windows explorer hitoxman 3 734 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,017 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Rename all files in a folder hitoxman 9 1,482 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  does not save in other path than opened files before icode 3 897 Jun-23-2023, 07:25 PM
Last Post: snippsat
  How to loop through all excel files and sheets in folder jadelola 1 4,459 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  python gzip all files from a folder mg24 3 3,977 Oct-28-2022, 03:59 PM
Last Post: mg24
  delete all files and subdirectory from a main folder mg24 7 1,584 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  Merge all json files in folder after filtering deneme2 10 2,335 Sep-18-2022, 10:32 AM
Last Post: deneme2

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020