Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将随机数写入文件并返回其平方_Python_Math_File Io_Python 3.x - Fatal编程技术网

Python 将随机数写入文件并返回其平方

Python 将随机数写入文件并返回其平方,python,math,file-io,python-3.x,Python,Math,File Io,Python 3.x,因此,我试图写一个随机数量的随机整数(在0到1000的范围内),将这些数字平方,然后将这些平方作为列表返回。起初,我开始编写一个我已经创建的特定txt文件,但它不能正常工作。我寻找了一些可以使事情变得更简单的方法,我发现了我认为可能有用的tempfile.NamedTemporaryFile方法。以下是我当前的代码,并提供了注释: # This program calculates the squares of numbers read from a file, using several fu

因此,我试图写一个随机数量的随机整数(在
0
1000
的范围内),将这些数字平方,然后将这些平方作为列表返回。起初,我开始编写一个我已经创建的特定txt文件,但它不能正常工作。我寻找了一些可以使事情变得更简单的方法,我发现了我认为可能有用的
tempfile.NamedTemporaryFile
方法。以下是我当前的代码,并提供了注释:

# 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)
#此程序使用多个函数计算从文件中读取的数字的平方
#读取文件-或将随机数的整数写入文件-通过数字循环
#并返回(x*x)或(x**2)的计算结果;
#结果存储在列表中并返回。
#更新1:出现错误和逻辑问题后,找到Python方法tempfile.NamedTemporaryFile:
#此函数的操作与TemporaryFile()完全相同,只是保证文件在文件系统中有一个可见的名称,并创建一个可以写入和访问的临时文件
#(例如,用于生成一个文件,其中包含每次都是随机的整数列表)。
导入随机、临时文件
#以随机长度写入临时文件(file_len>=1,但默认情况下会创建一个二进制文件(
mode='w+b'
)。要以文本模式打开文件并能够写入文本字符串(而不是字节字符串),需要更改临时文件创建调用,使其不使用
mode
参数中的
b
mode='w+'
):


您需要在每个int之后添加换行符,以免它们一起运行,形成一个巨大的整数:

newFile.write(str(random.randint(0, 1000))+'\n')
(同时设置模式,如PedroRomano的回答所述):


modfile返回一个关闭的文件句柄。您仍然可以从中获取文件名,但无法从中读取。因此,在
modfile
中,只需返回文件名:

   return newFile.name
在程序的主要部分,将文件名传递给
squared_num
函数:

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

现在在
squared_num
中,您需要打开文件进行读取

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

总而言之:

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)

注:不要在不运行它的情况下编写大量代码。编写少量函数,并测试每个函数是否按预期工作。例如,测试
modfile
会发现所有随机数都被串联。打印发送到
squared_num
的参数会显示它是一个闭合的文件句柄


测试这些片段为你提供了坚实的立足点,让你有条理地发展。

不应该
exp=newFile(l)**2
be
exp=int(l)**2
?(而且
l
作为一个名字从来都不是好的-
line
会是一个更好的名字为什么不使用[random.randit(01000)**2表示范围内的i(random.random.randint(01000))]?谢谢Pedro。现在很容易理解。谢谢unutbu。请原谅我的业余语法错误。我仍在学习…问题:当你返回这个临时文件时,它是否每次都自动关闭?其余的似乎都是不言自明的。再次感谢。当你用tempfile.NamedTemporaryFile(…)说
作为newFile
,或作为newFile
打开(…)的
,当Python使用
-block离开
时,会自动关闭文件句柄
newFile
。如果不想关闭文件句柄,请使用
newFile=tempfile.NamedTemporaryFile(…)
。但我不建议在这里使用,因为您还需要处理一些其他问题:(1)记得自己调用
newFile.close()
。(2)调用
newFile.seek(0)
以允许从文件的开头读取。有关
的更多信息,请参阅。
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
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)