如何使Python变量读取.txt配置文件中的指定目标数值?
Hey there! I've got you covered for this calculator project. Let's walk through exactly how to read that config file and set your var3 variable correctly.
Step-by-Step Implementation
First, let's outline the core tasks we need to handle:
- Locate and read the config file at the specified path (note that the
#in the path is fine as long as we use a raw string in Python) - Parse the file content to extract the target value (supporting both the
numbertoturninto=*anynumber*format and just a plain number like your example) - Convert the extracted value to a numeric type (integer or float) and assign it to
var3 - Handle common errors like missing files, invalid formats, or non-numeric values
Complete Code Example
Here's a robust script that handles all these cases:
var3 = None config_path = r'c:/python/calc2#/config.txt' # Raw string prevents issues with the # character try: with open(config_path, 'r') as config_file: # First, check for the key-value format for line in config_file: cleaned_line = line.strip() if cleaned_line.startswith('numbertoturninto='): # Split once to avoid issues if the value contains = (unlikely, but safe) _, target_str = cleaned_line.split('=', 1) target_str = target_str.strip() # Try converting to int first, then float for broader compatibility try: var3 = int(target_str) except ValueError: var3 = float(target_str) break # If no key-value line found, try reading the entire content as a plain number if var3 is None: config_file.seek(0) # Reset file pointer to start raw_content = config_file.read().strip() if not raw_content: raise ValueError("Config file is empty") try: var3 = int(raw_content) except ValueError: var3 = float(raw_content) except FileNotFoundError: print(f"Error: Could not find config file at {config_path}") except ValueError as ve: print(f"Error: Invalid value in config file - {ve}") except Exception as e: print(f"Unexpected error occurred: {e}") # Verify the result if var3 is not None: print(f"Success! var3 has been set to: {var3}")
How It Works
Let's break down the key parts:
- Raw String Path: Using
r'path'tells Python to treat the string literally, so the#incalc2#doesn't get interpreted as a comment. - Key-Value Parsing: We loop through each line to find the
numbertoturninto=entry, split it once to get the value, then convert it to a number. - Fallback to Plain Number: If the config file just has a raw number (like your example with
4), we reset the file pointer and read the entire content to convert it. - Error Handling: We catch common issues like missing files, empty files, and non-numeric values to make the script more reliable.
Test Cases
Case 1: Config file uses key-value format
config.txt content:
numbertoturninto=4
Result: var3 becomes 4 (integer)
Case 2: Config file has a plain decimal number
config.txt content:
3.14
Result: var3 becomes 3.14 (float)
Case 3: Config file has key-value with float
config.txt content:
numbertoturninto=9.81
Result: var3 becomes 9.81 (float)
内容的提问来源于stack exchange,提问作者Robotech Gamer
相关产品推荐
相关产品推荐

