Python生成随机整数写入文件报TypeError,MacBook Air环境求解决
Fixing Your Random Integer File Writer Code
Hey there! Let's sort out this issue for you first: this error has nothing to do with your MacBook Air—it's purely a code logic and typo problem. Let's break down what's wrong and how to fix it:
Key Issues in Your Code
- TypeError Cause: The
input()function returns a string, butrange()requires an integer. When you pass the user input directly torange(), Python can't convert that string to an integer automatically, hence the error. - Filename Typo: You're writing to
Random_intger.txt(missing an 'e' in "integer") but trying to read fromRandom_integer.txt—so you're creating two different files, and the one you read is empty. - Poor Readability: You're writing each integer without a newline character, so all numbers will be squashed into one line in the file.
Corrected Code
import random # Get integer input properly with a default of 100 count = int(input("Enter the number of random integers to generate (default: 100): ") or 100) # Use a single variable for filename to avoid typos filename = "Random_integer.txt" # Write to file using 'with' statement (auto-closes file) with open(filename, "w") as afile: for _ in range(count): num = random.randint(1, 100) line = str(num) + "\n" # Add newline for clean formatting afile.write(line) print(num) print("\nReading the file now.") # Read from the same consistent file with open(filename, "r") as afile: print(afile.read())
What Changed?
- Converted Input to Integer: We wrap
input()withint()to turn the user's string input into a valid integer. Theor 100part ensures we default to 100 if the user just hits enter without typing anything. - Consistent Filename: Defining the filename once as a variable eliminates typos between writing and reading operations.
- Used
withStatement: This is Python's recommended practice for file handling—it automatically closes the file when we're done, so you don't have to remember to callafile.close(). - Added Newlines: Each integer is followed by
\n, so each number appears on its own line in the file and when printed.
Why the Original File Was Empty
The error occurred before the loop could even run (since range(input(...)) fails immediately), so the file was created but no content was written to it. Fixing the input conversion will let the loop execute properly and write the random integers as intended.
内容的提问来源于stack exchange,提问作者Bob Cortana
相关产品推荐
相关产品推荐

