You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输出文本文件无法正常显示数据,总统名单查询代码求助

Hey there! Let's troubleshoot why adding the file-writing logic is causing your code to throw errors. Since your code worked fine before adding that part, the issue is almost certainly tied to how you're handling the output file or edge cases you didn't account for. Here are the most common fixes and best practices to get it working:

Common Issues & Fixes

1. File Handling Mistakes (The #1 Culprit)

If you're manually opening the output file with open() but forgetting to call close(), your data might not actually write to the file (due to buffer flushing) or could cause resource leaks that trigger errors. The safest way to handle files in Python is using the with statement, which automatically closes the file for you once you're done.

Bad practice (likely what's causing your issue):

# Risky: Forgetting to close the file
out_file = open("presidents_output.txt", "w")
for president in selected_presidents:
    out_file.write(president + "\n")
# No out_file.close() → data might not save, or file stays locked

Fixed version:

# Safe: with statement handles closing automatically
with open("presidents_output.txt", "w") as out_file:
    for president in selected_presidents:
        out_file.write(f"{president}\n")

2. Range & Index Mismatches

Since your input is a 1-based range (1 to 44 for presidents), but Python lists are 0-indexed, you might be accidentally accessing an index out of bounds when writing. Double-check that you're converting the user's start/end numbers correctly:

  • If user enters start=1, the index should be 0
  • If user enters end=5, the index should go up to 4 (since range() is exclusive of the end value)

Example of correct conversion:

start = int(input("Enter start number: "))
end = int(input("Enter end number: "))

# Convert to 0-indexed range
selected_indices = range(start - 1, end)

3. Missing Input Validation

If the user enters a range outside 1-44, or a start number greater than the end, your code will throw an IndexError when trying to access the president list. Adding validation before writing prevents this:

if not (1 <= start <= end <= 44):
    print("Oops! Please enter a valid range between 1 and 44, with start ≤ end.")
else:
    # Proceed with writing to file
    ...

4. Uncaught Exceptions

Without error handling, you'll get a generic error message that doesn't tell you what's wrong. Add try-except blocks to catch specific issues like invalid input, missing files, or permission errors:

try:
    start = int(input("Enter start number (1-44): "))
    end = int(input("Enter end number (1-44): "))
    # Rest of your code here
except ValueError:
    print("Error: Please enter whole numbers for the range.")
except PermissionError:
    print("Error: You don't have permission to write to the output file location.")
except FileNotFoundError:
    print("Error: Couldn't find the presidents.txt file.")

Full Working Example

Putting it all together, here's a revised version of your code that should work reliably:

# Read presidents from file (strip whitespace and skip empty lines)
with open("presidents.txt", "r") as in_file:
    presidents = [line.strip() for line in in_file if line.strip()]

try:
    # Get and validate user input
    start = int(input("Enter start president number (1-44): "))
    end = int(input("Enter end president number (1-44): "))
    
    if not (1 <= start <= end <= 44):
        print("Invalid range! Make sure start ≤ end and both are between 1 and 44.")
    else:
        # Write selected presidents to output file
        with open("selected_presidents.txt", "w") as out_file:
            for idx in range(start - 1, end):
                out_file.write(f"{presidents[idx]}\n")
        print(f"Success! Presidents {start} to {end} have been written to selected_presidents.txt.")

except ValueError:
    print("Please enter valid integers for the range.")
except IndexError:
    print("Error: The range you entered is outside the list of presidents.")
except Exception as e:
    print(f"Unexpected error: {str(e)}")

If you're still seeing errors, share the exact traceback message you get—that will help narrow down the problem even further!

内容的提问来源于stack exchange,提问作者J Money

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:10:29