96.8k views
3 votes
Write a program that

1. Walks through a directory tree (os.walk()) and searches for files with an extension of .pdf.
2. Print these files with their absolute path and file size to the screen.
3. Copy these files from whatever location they are into a new folder.

User Lizzett
by
5.2k points

1 Answer

1 vote

Answer:

import os

import shutil

# directory holding the file to be used

curr_path = "C:\\Users\\user\\Desktop\\test"

# change to the target directory absolute path

os.chdir(curr_path)

# create new folder in current directory

os.mkdir('C:\\Users\\user\\Desktop\\\ewFolder')

for root, dirs, files in os.walk("."):

for name in files:

# check if it is pdf

if name.endswith(".pdf"):

# find path

path = os.path.join(root, name)

# find size

size = os.stat(path).st_size

# print absolute path and size

print(os.path.abspath(path), "\t", size)

# copy the file to the new folder

shutil.copy(path, 'C:\\Users\\user\\Desktop\\\ewFolder\\'+name)

Step-by-step explanation:

The python program uses the os and shutil python module, which is used to interact with the computer system operating system to get the absolute path of all the pdf text files using the os.walk() method to create an iterator to loop over, printing the path string and the file size. The shutil.copy() is used to make a copy of each pdf file in the new folder.

User ITollu
by
4.7k points