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

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, but range() requires an integer. When you pass the user input directly to range(), 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 from Random_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() with int() to turn the user's string input into a valid integer. The or 100 part 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 with Statement: 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 call afile.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 07:04:37