Python 3读取文本文件求温最值出错,寻求代码修正方案
Hey there! Let's work through why your Python script isn't correctly pulling the lowest and highest temperature values from your text file—since you're new to this, I'll break this down into easy-to-follow checks and fixes.
1. Match your code to your text file's format
First off, double-check what each line in open_File.txt looks like. Is it structured something like 02/01,2002,12,35 (date, year, low temp, high temp)? If your code is grabbing values from the wrong positions (like slicing the string incorrectly, or using the wrong delimiter with split()), it'll pull random bits (like parts of the date/year) instead of actual temperatures—exactly what's happening with your output showing 8 and 77 as temps.
2. Fix your initial temperature variable setup
I noticed you initialized lowest = 200—that's way too high if your actual low temps are normal weather values! If all your real low temps are below 200, this value will never get updated, leaving you with a wrong result. Instead:
- Set the initial lowest temp to a really high number (like
float('inf'), which means "infinity") - Set the initial highest temp to a really low number (like
float('-inf'))
This way, any valid temperature from your file will replace these starting values.
3. Convert text values to numbers
When you read from a text file, everything is a string. If you compare strings directly (like "8" vs "10"), Python will sort them alphabetically instead of numerically. That means "10" would be considered smaller than "8"—totally wrong for temperatures! Always convert your temp strings to int or float before comparing.
Example Fixed Code
Here's a revised version of your script that addresses all these issues, assuming your text file uses commas to separate each value:
def main(): # Use a `with` statement to auto-close the file (safer than just open()) with open('open_File.txt', 'r') as file: # Initialize extremes with values that will definitely be replaced lowest_temp = float('inf') highest_temp = float('-inf') lowest_day, lowest_year = "", "" highest_day, highest_year = "", "" for line in file: # Clean up the line and skip empty ones cleaned_line = line.strip() if not cleaned_line: continue # Split the line into parts based on commas data_parts = cleaned_line.split(',') # Skip lines that don't have 4 values (date, year, low, high) if len(data_parts) != 4: print(f"Skipping invalid line: {cleaned_line}") continue day, year, low_str, high_str = data_parts # Convert temps to integers (use float if you have decimals) try: low_temp = int(low_str) high_temp = int(high_str) except ValueError: print(f"Invalid temperature in line: {cleaned_line}") continue # Update lowest temp record if low_temp < lowest_temp: lowest_temp = low_temp lowest_day = day lowest_year = year # Update highest temp record if high_temp > highest_temp: highest_temp = high_temp highest_day = day highest_year = year # Print the final results print(f"Day: {lowest_day} Year: {lowest_year} The lowest temp is: {lowest_temp}") print(f"Day: {highest_day} Year: {highest_year} The highest temp is: {highest_temp}") if __name__ == "__main__": main()
Quick Extra Checks
- File Path: If
open_File.txtisn't in the same folder as your script, use the full file path (like'C:/my_files/open_File.txt'on Windows or'/home/user/my_files/open_File.txt'on macOS/Linux) - Delimiter: If your file uses spaces instead of commas, change
split(',')tosplit()(which splits on any whitespace)
内容的提问来源于stack exchange,提问作者user9680245

