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 toinput()instead ofopen(). 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:
- Fixed
open()syntax: Separated theinput()call (to get the filename) from theopen()call (where we specify write mode'w'). - Added positive number check: Ensures the user can't ask for zero or negative random numbers, which would break the loop.
- Used
withstatements: This automatically closes the file when we're done with it—no more forgetting to callclose(), which can cause file access issues. - Implemented file read/print: After writing, we reopen the file in read mode (
'r'), read its full content, and print it out. - 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
相关产品推荐
相关产品推荐

