Python CSV文件查询:开发根据城市获取对应文件完整路径的交互式代码
Hey there! Let's build a simple interactive Python script that does exactly what you need—letting users input a city name and getting the full path to the corresponding CSV file. Here's a step-by-step solution:
Interactive City CSV Path Lookup Tool
How it works
We'll create a script that:
- Stores the mapping between city names and their CSV filenames (or dynamically generates filenames if they follow a strict pattern)
- Takes user input for the city
- Validates the input and returns the full file path (with error handling for invalid cities or missing files)
Full Code Example
import os def retrieve_city_csv_path(): # Update this to the actual directory where your CSV files are stored csv_directory = "/your/actual/csv/directory/path" # Map city names to their corresponding CSV filenames # Replace these with your actual city names and file names city_to_csv = { "Beijing": "beijing_data.csv", "Shanghai": "shanghai_metrics.csv", "Guangzhou": "guangzhou_stats.csv" } # Get user input with cleanup to avoid accidental spaces user_city = input("Please enter the city name to look up: ").strip() # Check if the city is supported if user_city in city_to_csv: # Build the full path safely (works across Windows/macOS/Linux) full_file_path = os.path.join(csv_directory, city_to_csv[user_city]) # Optional: Verify the file actually exists for robustness if os.path.isfile(full_file_path): print(f"✅ Full path to the CSV file: {full_file_path}") return full_file_path else: print(f"❌ Error: File not found at {full_file_path}. Please check the file exists.") else: supported_cities = ", ".join(city_to_csv.keys()) print(f"❌ Error: '{user_city}' is not a supported city. Supported cities are: {supported_cities}") # Run the interactive function if __name__ == "__main__": retrieve_city_csv_path()
Key Customization Points
- CSV Directory: Change
csv_directoryto the real folder where your CSV files live. Usingos.path.joinensures the path works seamlessly across different operating systems. - City-to-File Mapping: Update
city_to_csvwith your three cities and their exact CSV filenames. If your CSVs are named exactly like the city (e.g., "Chengdu.csv" for Chengdu), you can simplify this to a list and generate the filename dynamically:supported_cities = ["Chengdu", "Shenzhen", "Hangzhou"] if user_city in supported_cities: full_file_path = os.path.join(csv_directory, f"{user_city}.csv") - Error Handling: The script checks for both invalid city names and missing files, which makes it more reliable for real-world use cases.
Quick Tips
- If you plan to add more cities later, just update the mapping/list—no need to rewrite the core logic.
- For larger projects, you could store the city list and CSV directory in a config file (like
config.json) to keep your code clean and easy to maintain.
内容的提问来源于stack exchange,提问作者python_newbie
相关产品推荐
相关产品推荐

