如何用Python 3读取CSV构造指定字典并通过API PUT上传数据
Here's a straightforward, practical way to read your CSV, build the required dictionary structure, and send it to your website's API using Python 3:
1. Import Required Libraries
First, we’ll use Python’s built-in csv module to parse the CSV file, and the requests library to handle the API request. If you don’t have requests installed, run pip install requests in your terminal first.
import csv import requests
2. Read the CSV and Build the Target Dictionary
We’ll use csv.DictReader to easily map each row to its column headers, then construct your desired dictionary by iterating through each row. We’ll also strip any extra whitespace from the CSV values (since your sample has spaces after commas):
data = {} # Replace 'your_devices.csv' with the path to your actual CSV file with open('your_devices.csv', mode='r', newline='', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: # Clean up whitespace from each value to avoid formatting issues mac = row['MAC'].strip() ip = row['IP'].strip() name = row['NAME'].strip() # Add the entry to our data dictionary data[mac] = { 'ip': ip, 'name': name } # Optional: Print the result to verify the structure matches your needs print(data)
Running this will produce exactly the dictionary format you specified:
{'MA:C0:AD:DR:ES:S1': {'ip': '1.1.1.1', 'name': 'TEST'}, 'MA:C0:AD:DR:ES:S2': {'ip': '2.2.2.2', 'name': 'TEST2'}, ...}
3. Send the PUT Request to the API
Now we’ll use requests.put() to send the data to your website’s API. Replace 'https://your-api-endpoint.com/upload' with your actual API URL. If your API requires authentication (like a bearer token), add the necessary headers:
api_url = 'https://your-api-endpoint.com/upload' # Optional: Add authentication or content-type headers if required by your API headers = { 'Authorization': 'Bearer YOUR_AUTH_TOKEN', # Example token format (adjust as needed) 'Content-Type': 'application/json' # Most APIs expect JSON payloads } try: # Send the PUT request with our data formatted as JSON response = requests.put(api_url, json=data, headers=headers) # Check if the request was successful response.raise_for_status() print("Data uploaded successfully!") print("API Response:", response.json()) # Print the API's feedback if useful except requests.exceptions.RequestException as e: print(f"Error uploading data: {e}")
Key Tips for Success
- CSV Consistency: Ensure your CSV uses exactly the column headers
MAC,IP,NAME(case-sensitive—adjust the code if your headers are different). - Whitespace Cleanup: The
.strip()method is crucial to avoid invalid MAC addresses/IPs caused by extra spaces in the CSV. - API Details: Double-check your API docs for:
- Confirmation that the endpoint accepts PUT requests
- Any required authentication tokens or headers
- Limits on the size of a single request (split large CSVs into batches if needed)
内容的提问来源于stack exchange,提问作者PythonFreak

