I’m trying to run a Python script that saves the names of folders in an FTP (1 subfolder deep) into a CSV, but it only saves the name of a single folder into my CSV before stopping without errors.
I’m not using the root login to connect since I didn’t assume I need to. I’m just trying to figure out if it’s the script or my FTP permissions that I need to fix.
import time
from ftplib import FTP, error_perm
import csv
import socket
# --- FTP Configuration ---
ftp_host = "XXX"
ftp_user = "XXX"
ftp_pass = "XXX"
# --- FTP Connection Parameters ---
timeout = 60 # seconds
passive_mode = True # Set to True to use passive mode
# --- Connect to FTP ---
try:
ftp = FTP(ftp_host, timeout=timeout)
ftp.login(ftp_user, ftp_pass)
if passive_mode:
ftp.set_pasv(True) # Enable passive mode
except socket.timeout:
print("Error: Connection timed out.")
exit()
except Exception as e:
print(f"Error connecting to FTP: {e}")
exit()
def get_folders(path):
"""
Retrieves a list of folders and their immediate subfolders
from the given path on the FTP server.
Args:
path (str): The base path on the FTP server.
Returns:
list: A list of tuples, where each tuple contains
the folder path and a list of its subfolders.
"""
folders = []
try:
ftp.cwd(path)
items = ftp.nlst()
for item in items:
try:
ftp.cwd(f"{path}/{item}")
ftp.cwd(path)
subfolders = []
for subitem in ftp.nlst(f"{path}/{item}"):
try:
ftp.cwd(f"{path}/{item}/{subitem}")
ftp.cwd(f"{path}/{item}")
subfolders.append(subitem)
except error_perm:
pass # Not a folder
folders.append((item, subfolders))
print(f"Processed folder: {path}/{item}")
time.sleep(0.1)
except error_perm:
pass # Not a folder
except Exception as e:
print(f"Error processing folder {path}: {e}")
return folders
# --- Get the folder structure ---
folder_data = get_folders("/") # Start from the root
# --- Save data to CSV ---
with open("ftp_folders.csv", "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Folder", "Subfolders"])
for folder, subfolders in folder_data:
writer.writerow([folder, ", ".join(subfolders)])
print(f"Wrote folder to CSV: {folder}")
# --- Close the FTP connection ---
try:
ftp.quit()
except Exception as e:
print(f"Error closing FTP connection: {e}")
print("Folder data extracted and saved to ftp_folders.csv")
6