如何将变量用作目录?在FTP代码中用log_dir定位文件上传
Hey Matt, great questions—let's walk through how to solve this cleanly and reliably.
First: How to Use a Variable as a Directory Path
The key here is to dynamically build your file path using safe, cross-platform methods instead of hardcoding or manually string-concatenating paths (which breaks easily across Windows/macOS/Linux).
Python gives you two solid options for this:
- The traditional
os.pathmodule - The modern
pathliblibrary (Python 3.4+, highly recommended for readability)
Applying This to Your FTP Code
Since your key_log.txt is in the same directory as your script, setting log_dir = "" will work perfectly with either method—they'll default to the current working directory.
Option 1: Using os.path.join()
This method handles path separators (\ on Windows, / on Unix-like systems) automatically, so you don't have to worry about typos or system differences.
import os import ftplib # Your directory variable (empty = current directory) log_dir = "" # Build the full path to your log file file_path = os.path.join(log_dir, "key_log.txt") # Open the file and upload via FTP (using a `with` statement to auto-close the file) with open(file_path, 'rb') as fh: ftp = ftplib.FTP("your-ftp-server.com") ftp.login("your-username", "your-password") ftp.storbinary("STOR key_log.txt", fh) # "STOR" tells FTP to store the file ftp.quit()
Option 2: Using pathlib (Modern Approach)
pathlib uses object-oriented syntax, making path operations more intuitive. The / operator acts as a path separator—super clean!
from pathlib import Path import ftplib log_dir = "" # Build the path (empty log_dir means current directory) file_path = Path(log_dir) / "key_log.txt" # Use pathlib's built-in open method (still with `with` for safety) with file_path.open('rb') as fh: ftp = ftplib.FTP("your-ftp-server.com") ftp.login("your-username", "your-password") ftp.storbinary("STOR key_log.txt", fh) ftp.quit()
Bonus: Handling Non-Existent Directories
If you ever change log_dir to a directory that doesn't exist yet (e.g., log_dir = "./archive/logs"), you can add a line to create the directory automatically:
- For
os.path:os.makedirs(os.path.dirname(file_path), exist_ok=True) - For
pathlib:file_path.parent.mkdir(parents=True, exist_ok=True)
The exist_ok=True flag prevents errors if the directory already exists.
内容的提问来源于stack exchange,提问作者Matt J

