Skip to content

Commit 67001a2

Browse files
committed
added listing files & directories in ftp server tutorial
1 parent a8e8d52 commit 67001a2

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,5 +86,6 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
8686
- [How to Handle Files in Python using OS Module](https://www.thepythoncode.com/article/file-handling-in-python-using-os-module). ([code](python-standard-library/handling-files))
8787
- [How to Generate Random Data in Python](https://www.thepythoncode.com/article/generate-random-data-in-python). ([code](python-standard-library/generating-random-data))
8888
- [How to Use Threads to Speed Up your IO Tasks in Python](https://www.thepythoncode.com/article/using-threads-in-python). ([code](python-standard-library/using-threads))
89+
- [How to List all Files and Directories in FTP Server using Python](https://www.thepythoncode.com/article/list-files-and-directories-in-ftp-server-in-python). ([code](python-standard-library/listing-files-in-ftp-server))
8990

9091
For any feedback, please consider pulling requests.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# [How to List all Files and Directories in FTP Server using Python](https://www.thepythoncode.com/article/list-files-and-directories-in-ftp-server-in-python)
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import ftplib
2+
import os
3+
from datetime import datetime
4+
5+
FTP_HOST = "ftp.ed.ac.uk"
6+
FTP_USER = "anonymous"
7+
FTP_PASS = ""
8+
# FTP_HOST = "192.168.1.1"
9+
# FTP_USER = "admin"
10+
# FTP_PASS = "586290929699"
11+
12+
# some utility functions that we gonna need
13+
def get_size_format(n, suffix="B"):
14+
# converts bytes to scaled format (e.g KB, MB, etc.)
15+
for unit in ["", "K", "M", "G", "T", "P"]:
16+
if n < 1024:
17+
return f"{n:.2f}{unit}{suffix}"
18+
n /= 1024
19+
20+
21+
def get_datetime_format(date_time):
22+
# convert to datetime object
23+
date_time = datetime.strptime(date_time, "%Y%m%d%H%M%S")
24+
# convert to human readable date time string
25+
return date_time.strftime("%Y/%m/%d %H:%M:%S")
26+
27+
28+
# initialize FTP session
29+
ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)
30+
# force UTF-8 encoding
31+
ftp.encoding = "utf-8"
32+
# print the welcome message
33+
print(ftp.getwelcome())
34+
# change the current working directory to 'pub' folder and 'maps' subfolder
35+
ftp.cwd("pub/maps")
36+
37+
# LIST a directory
38+
print("*"*50, "LIST", "*"*50)
39+
ftp.dir()
40+
41+
# NLST command
42+
print("*"*50, "NLST", "*"*50)
43+
print("{:20} {}".format("File Name", "File Size"))
44+
for file_name in ftp.nlst():
45+
file_size = "N/A"
46+
try:
47+
ftp.cwd(file_name)
48+
except Exception as e:
49+
ftp.voidcmd("TYPE I")
50+
file_size = get_size_format(ftp.size(file_name))
51+
print(f"{file_name:20} {file_size}")
52+
53+
54+
print("*"*50, "MLSD", "*"*50)
55+
# using the MLSD command
56+
print("{:30} {:19} {:6} {:5} {:4} {:4} {:4} {}".format("File Name", "Last Modified", "Size",
57+
"Perm","Type", "GRP", "MODE", "OWNER"))
58+
for file_data in ftp.mlsd():
59+
# extract returning data
60+
file_name, meta = file_data
61+
# i.e directory, file or link, etc
62+
file_type = meta.get("type")
63+
if file_type == "file":
64+
# if it is a file, change type of transfer data to IMAGE/binary
65+
ftp.voidcmd("TYPE I")
66+
# get the file size in bytes
67+
file_size = ftp.size(file_name)
68+
# convert it to human readable format (i.e in 'KB', 'MB', etc)
69+
file_size = get_size_format(file_size)
70+
else:
71+
# not a file, may be a directory or other types
72+
file_size = "N/A"
73+
# date of last modification of the file
74+
last_modified = get_datetime_format(meta.get("modify"))
75+
# file permissions
76+
permission = meta.get("perm")
77+
78+
# get the file unique id
79+
unique_id = meta.get("unique")
80+
# user group
81+
unix_group = meta.get("unix.group")
82+
# file mode, unix permissions
83+
unix_mode = meta.get("unix.mode")
84+
# owner of the file
85+
unix_owner = meta.get("unix.owner")
86+
# print all
87+
print(f"{file_name:30} {last_modified:19} {file_size:7} {permission:5} {file_type:4} {unix_group:4} {unix_mode:4} {unix_owner}")
88+
89+
90+
# quit and close the connection
91+
ftp.quit()

0 commit comments

Comments
 (0)