write()创建空fi

2024-09-26 22:52:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个文件,但是如果我以open(file,"w")的形式打开,它输出一个空白文件,它确实可以与open(file,"a")一起工作,但我不想追加,因为它变得非常大,非常快,我只需要更新文件。在

代码如下:

p1 = open("C:\\Users\\JoãoPedro\\Documents\\Python\\PrimeFactoring\\primes1.txt","r")
Prime_list = p1.read()
Prime_list = Prime_list.split()
p1.close()

L_List = len(Prime_list)
i = 29420
x = [Here goes a really large number]
while (i <= L_List):
   Primorial_List = open("Primorial.txt","w")
   Primorial_List.write("%d :: %s :: %d \n"%(i,Prime_list[i],x))
   Primorial_List.close()
   print(str(i) + " :: " + Prime_list[i])

   i += 1
   x = x * int(Prime_list[i])

print("Finished")

代码上的缩进是正确的,但我不知道为什么我不能在这里缩进代码:/

我注意到的一件事是,我没有以管理员的身份运行空闲程序,我应该这样做吗?在


Tags: 文件代码txtcloseopenusersprime空白
3条回答

由于这些原因,您的代码应该在while结束时给出索引器错误

i += 1
x = x * int(Prime_list[i])

更不用说还有一个

^{pr2}$

这将允许再进行一次迭代,从而使用Primorial生成索引器_列表.写入也。如果你的代码运行正常,你应该检查是否有任何尝试。。。除非用它来调用这段代码。在那里你可以找到清空文件的原因。在某个地方,您可能只是在这段代码之后打开并关闭文件?或者类似这样的逻辑等价物可能是原因:

while (i <= L_List):

    Primorial_List = open("Primorial.txt","w")
    try:
        Primorial_List.write("%d :: %s :: %d \n"%(i,Prime_list[i],x))
    except:
        pass
    Primorial_List.close()

或者像这样:

try:
    while (i <= L_List):
        Primorial_List = open("Primorial.txt","w")
        Primorial_List.write("%d :: %s :: %d \n"%(i,Prime_list[i],x))
        Primorial_List.close()
except:
    pass

也就是说密码会从Primorial移走_列表.写入方法,因为它将导致上一次迭代的索引器错误,因为Prime\u list[i]。在

万一没有尝试。。。除了blocks之外,我假设您已经将I+=1语句推送到x=x*Prime_list[I]旁边,这也会使文件为空,但在结尾处以IndexError结尾。在

另一方面,正如其他人提到的,您应该打开一次文件并写入一次,而不是连续写入。更好的是,使用Python的with语句进行文件操作。以下可能是等效的:-)

with open("C:\\Users\\JoãoPedro\\Documents\\Python\\PrimeFactoring\\primes1.txt") as fo:
    Prime_list = fo.read()

Prime_list = Prime_list.split()
L_List = len(Prime_list)
i = 29420
x = [Here goes a really large number]

new_file_content = ""
while (i < L_List):
   new_file_content += "%d :: %s :: %d \n"%(i,Prime_list[i],x)
   print(str(i) + " :: " + Prime_list[i])
   x = x * int(Prime_list[i])
   i += 1

with open("Primorial.txt", "w") as fo:
    fo.write(new_file_content)

print("Finished")

而不是:

while (i <= L_List):
   Primorial_List = open("Primorial.txt","w")
   Primorial_List.write("%d :: %s :: %d \n"%(i,Prime_list[i],x))
   Primorial_List.close()
   print(str(i) + " :: " + Prime_list[i])

   i += 1
   x = x * int(Prime_list[i])

如果你做了以下事情会怎么样:

^{pr2}$

正如@Barmar所提到的-你现在的方式是每次都重写文件(如你所愿),正如@John Zwinck所说,这是非常浪费的-只要你能(做你所有的计算)呆在Python中,只写一次,就写一次。在

Primorial_List = open("Primorial.txt","w")
while (i <= L_List):
    Primorial_List.write("%d :: %s :: %d \n"%(i,Prime_list[i],x))
    Primorial_List.close()
    print(str(i) + " :: " + Prime_list[i])
    i += 1
    x = x * int(Prime_list[i])
Primorial_List.close()

重新格式化代码以在循环之前打开文件,并在完成时关闭,这样可以使它正常工作并创建一个包含数据的文件。在

相关问题 更多 >

    热门问题