python -m idlelib无法保存文件中的输出

时间:2018-06-06 11:29:21

标签: python save multiprocessing

我复制并粘贴了以下this site代码。我在Windows上,而不是IDLE我在C:\Users\MyName>python -m idlelib中使用command prompt而且效果很好。

from multiprocessing import Process


def square(numbers):

    for x in numbers:
        print('%s squared  is  %s' % (x, x**2))

if __name__ == '__main__':
    numbers = [43, 50, 5, 98, 34, 35]

    p = Process(target=square, args=(numbers,))
    p.start()
    p.join()
    print ("Done")

现在我将上面的代码更改为以下代码,以便将输出保存在文件中。

from multiprocessing import Process

with open('outputs/multip.txt', 'w') as f:
    def square(numbers):

        for x in numbers:
            f.write("{0}\t{1}\t{2}\n".format(x,'squared  is',x**2))

if __name__ == '__main__':
    numbers = [43, 50, 5, 98, 34, 35]

    p = Process(target=square, args=(numbers,))
    p.start()
    p.join()
    print ("Done")

我创建了一个文件夹outputs,当我使用with open('outputs/multip.txt', 'w')时,我在命令提示符Error[2] no such file or directory中看到错误。

当我刚使用with open('multip.txt', 'w')时,它会获得i/o operation on closed file

有什么问题?

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

  1. No such file or directory

    with open(os.path.join(os.getcwd(),'outputs/multip.txt', 'w')) as ....:
    
  2. 2.对于错误I/O operation on closed file

    def square(numbers):
         with open(os.path.join(os.getcwd(),'outputs/multip.txt', 'w')) as f:
    

    打开函数内的文件并对其执行操作

答案 1 :(得分:0)

您应该使用完整路径,如下所示。

from multiprocessing import Process
import os
import sys

def square(numbers):
    pat='C:/Users/esadr21/Desktop/MHT/Models/outputs'
    file_path = os.path.join(pat,'multip.txt')
    with open(file_path, 'w') as f:
        for x in numbers:
            f.write("{0}\t{1}\t{2}\n".format(x,'squared  is',x**2))

if __name__ == '__main__':
    numbers = [43, 50, 5, 98, 34, 35]

    p = Process(target=square, args=(numbers,))
    p.start()
    p.join()
    print ("Done")