Python从文件读取列表:语法与文件格式修正求助
Hey Paul, let's get that hardcoded server list moved to a file so you can scale it easily! I'll walk you through a few simple, reliable methods that should work right away—no more struggling with uncooperative file reads.
Method 1: Simple Text File (Comma-Separated)
This is the easiest approach, no extra libraries required.
First, create a text file named servers.txt with one server entry per line, separating the domain and tag with a comma:
abc.com,abc def.com,def hji.com,hji
Then update your Python code to read this file and build your serverlist:
serverlist = [] # Use a 'with' statement to safely handle file operations (it auto-closes the file) with open('servers.txt', 'r') as f: for line in f: # Strip whitespace/newlines and skip empty lines cleaned_line = line.strip() if not cleaned_line: continue # Split the line into domain and tag, then add to the list domain, tag = cleaned_line.split(',') serverlist.append((domain, tag)) # Verify the result matches your original hardcoded list print(serverlist)
Method 2: CSV File (More Structured)
If you might expand the data later (or just want a standardized format), use Python's built-in csv module—it handles edge cases like unexpected whitespace automatically.
Create a servers.csv file with the same content as the text file above. Then use this code:
import csv serverlist = [] with open('servers.csv', 'r') as f: # Create a CSV reader to parse the file reader = csv.reader(f) for row in reader: # Ensure each row has exactly two elements before adding if len(row) == 2: serverlist.append((row[0], row[1])) print(serverlist)
Method 3: JSON File (Great for Complex Data)
JSON is perfect if you ever need to add more fields per server (like ports or credentials). First create a servers.json file:
[ ["abc.com", "abc"], ["def.com", "def"], ["hji.com", "hji"] ]
Then read it in Python and convert the JSON lists to tuples (to match your original data structure):
import json with open('servers.json', 'r') as f: # Load JSON data and convert each entry to a tuple serverlist = [tuple(entry) for entry in json.load(f)] print(serverlist)
Pro Tips to Avoid Common Headaches
- File Paths: If your file isn't in the same folder as your script, use the full absolute path (e.g.,
C:/my_project/servers.txton Windows or/home/user/my_project/servers.txton Linux/macOS). - Error Handling: Add basic checks to catch missing files or malformed lines:
serverlist = [] try: with open('servers.txt', 'r') as f: for line in f: cleaned_line = line.strip() if not cleaned_line: continue parts = cleaned_line.split(',') if len(parts) != 2: print(f"Skipping invalid line: {cleaned_line}") continue serverlist.append((parts[0], parts[1])) except FileNotFoundError: print("Oops! Couldn't find the servers.txt file.") except Exception as e: print(f"Something went wrong: {str(e)}")
内容的提问来源于stack exchange,提问作者Paul B

