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

Python程序无法写入指定文本文件的问题求助

Fixing Your Random Number File Generator

Hey there! Let's work through the issues in your code to get it fully functional—including writing the random numbers and then reading the file back to print its content.

First, let's spot the key problems in your original code:

  • Syntax mix-up in open(): You incorrectly passed the file mode ('w') as a second argument to input() instead of open(). That's why the file wasn't being created/written to properly.
  • Missing file read step: Your code stops after writing the numbers, but doesn't implement the requirement to open the file and print its content.
  • Incomplete error handling: You didn't account for cases like non-positive numbers or file system errors (e.g., permission issues).

Here's the corrected, fully functional code:

import random

try:
    # Get a valid positive integer for the number of random values
    amt_nums = int(input("Enter the amount of random numbers you want: "))
    if amt_nums <= 0:
        raise ValueError("Please enter a positive whole number")
    
    # Get the target filename and write the random numbers
    filename = input("Enter the filename to write to: ")
    # Use 'with' statement to auto-manage file closure (safer than manual close())
    with open(filename, 'w') as random_file:
        for _ in range(amt_nums):
            num = random.randint(1, 500)
            random_file.write(f"{num}\n")
            print(f"Generated: {num}")  # Optional: show each generated number
    
    # Now read and print the file's content
    print("\n--- File Content ---")
    with open(filename, 'r') as read_file:
        file_content = read_file.read()
        print(file_content)

except ValueError as ve:
    print(f"Input Error: {ve}")
except IOError as ie:
    print(f"File Error: {ie}")
except Exception as e:
    print(f"Unexpected Error: {e}")

What changed and why:

  1. Fixed open() syntax: Separated the input() call (to get the filename) from the open() call (where we specify write mode 'w').
  2. Added positive number check: Ensures the user can't ask for zero or negative random numbers, which would break the loop.
  3. Used with statements: This automatically closes the file when we're done with it—no more forgetting to call close(), which can cause file access issues.
  4. Implemented file read/print: After writing, we reopen the file in read mode ('r'), read its full content, and print it out.
  5. Enhanced error handling: We catch specific errors (like invalid integers, non-positive numbers, and file system issues) to give clear, helpful messages instead of generic errors.

内容的提问来源于stack exchange,提问作者Griffin Christoffers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:24:13