Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8771029
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T17:41:05+00:00 2026-06-13T17:41:05+00:00

So, I’m trying to write a random amount of random whole numbers (in the

  • 0

So, I’m trying to write a random amount of random whole numbers (in the range of 0 to 1000), square these numbers, and return these squares as a list. Initially, I started off writing to a specific txt file that I had already created, but it didn’t work properly. I looked for some methods I could use that might make things a little easier, and I found the tempfile.NamedTemporaryFile method that I thought might be useful. Here’s my current code, with comments provided:

# This program calculates the squares of numbers read from a file, using several functions
# reads file- or writes a random number of whole numbers to a file -looping through numbers
# and returns a calculation from (x * x) or (x**2);
# the results are stored in a list and returned.
# Update 1: after errors and logic problems, found Python method tempfile.NamedTemporaryFile: 
# This function operates exactly as TemporaryFile() does, except that the file is guaranteed to   have a visible name in the file system, and creates a temprary file that can be written on and accessed 
# (say, for generating a file with a list of integers that is random every time).

import random, tempfile 

# Writes to a temporary file for a length of random (file_len is >= 1 but <= 100), with random  numbers in the range of 0 - 1000.
def modfile(file_len):
       with tempfile.NamedTemporaryFile(delete = False) as newFile:
            for x in range(file_len):
                 newFile.write(str(random.randint(0, 1000)))
            print(newFile)
return newFile

# Squares random numbers in the file and returns them as a list.
    def squared_num(newFile):
        output_box = list()
        for l in newFile:
            exp = newFile(l) ** 2
            output_box[l] = exp
        print(output_box)
        return output_box

    print("This program reads a file with numbers in it - i.e. prints numbers into a blank file - and returns their conservative squares.")
    file_len = random.randint(1, 100)
    newFile = modfile(file_len)
    output = squared_num(file_name)
    print("The squared numbers are:")
    print(output)

Unfortunately, now I’m getting this error in line 15, in my modfile function: TypeError: 'str' does not support the buffer interface. As someone who’s relatively new to Python, can someone explain why I’m having this, and how I can fix it to achieve the desired result? Thanks!

EDIT: now fixed code (many thanks to unutbu and Pedro)! Now: how would I be able to print the original file numbers alongside their squares? Additionally, is there any minimal way I could remove decimals from the outputted float?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T17:41:06+00:00Added an answer on June 13, 2026 at 5:41 pm

    You need to put newlines after each int, lest they all run together creating a huge integer:

    newFile.write(str(random.randint(0, 1000))+'\n')
    

    (Also set the mode, as explained in PedroRomano’s answer):

       with tempfile.NamedTemporaryFile(mode = 'w+', delete = False) as newFile:
    

    modfile returns a closed filehandle. You can still get a filename out of it, but you can’t read from it. So in modfile, just return the filename:

       return newFile.name
    

    And in the main part of your program, pass the filename on to the squared_num function:

    filename = modfile(file_len)
    output = squared_num(filename)
    

    Now inside squared_num you need to open the file for reading.

    with open(filename, 'r') as f:
        for l in f:
            exp = float(l)**2       # `l` is a string. Convert to float before squaring
            output_box.append(exp)  # build output_box with append
    

    Putting it all together:

    import random, tempfile 
    
    def modfile(file_len):
           with tempfile.NamedTemporaryFile(mode = 'w+', delete = False) as newFile:
                for x in range(file_len):
                     newFile.write(str(random.randint(0, 1000))+'\n')
                print(newFile)
           return newFile.name
    
    # Squares random numbers in the file and returns them as a list.
    def squared_num(filename):
        output_box = list()
        with open(filename, 'r') as f:
            for l in f:
                exp = float(l)**2
                output_box.append(exp)
        print(output_box)
        return output_box
    
    print("This program reads a file with numbers in it - i.e. prints numbers into a blank file - and returns their conservative squares.")
    file_len = random.randint(1, 100)
    filename = modfile(file_len)
    output = squared_num(filename)
    print("The squared numbers are:")
    print(output)
    

    PS. Don’t write lots of code without running it. Write little functions, and test that each works as expected. For example, testing modfile would have revealed that all your random numbers were being concatenated. And printing the argument sent to squared_num would have shown it was a closed filehandle.

    Testing the pieces gives you firm ground to stand on and lets you develop in an organized way.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to select an H1 element which is the second-child in its group
I have an array which has BIG numbers and small numbers in it. I
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.