How to Retrieve All File Names in a Directory and Keep the Largest ZIP File Using Python
This article explains how to list all file names in a specified folder with os.listdir and os.path.isfile, shows a concise list‑comprehension version, and demonstrates how to retain only the largest ZIP file by sorting and deleting others using Python's os and glob modules.
To list all file names in a specific folder, you can use the os.listdir function combined with os.path.isfile to filter only files, as shown in the first example.
<code>import os
def get_file_names(folder_path):
file_names = []
for item in os.listdir(folder_path):
item_path = os.path.join(folder_path, item)
if os.path.isfile(item_path): # only process files, ignore directories
file_names.append(item) # add file name to list
return file_names
folder_path = "your_folder_path" # replace with your folder path
file_names = get_file_names(folder_path)
print(file_names)</code>The script iterates through the directory, checks each entry with os.path.isfile , and collects the file names into a list.
A more concise approach uses a list comprehension to achieve the same result in a single line.
<code>import os
def get_file_names(folder_path):
return [item for item in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, item))]
folder_path = "your_folder_path" # replace with your folder path
file_names = get_file_names(folder_path)
print(file_names)</code>This version leverages the syntax [expression for item in list if condition] to filter and collect file names.
To keep only the largest ZIP file in a directory, you can list all ZIP files with glob.glob , sort them by size using os.path.getsize , and delete the rest.
<code>import os
import glob
# specify folder path
folder_path = "/path/to/your/folder"
# get all zip files in the folder
zip_files = glob.glob(os.path.join(folder_path, "*.zip"))
# sort by file size descending
zip_files.sort(key=os.path.getsize, reverse=True)
# keep the largest zip, delete others
for i in range(1, len(zip_files)):
os.remove(zip_files[i])
print("保留最大的zip文件完成。")</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.