我复制并粘贴了这个网站的以下代码。我在窗户上,所以我在command prompt
中使用C:UsersMyName>python -m idlelib
而不是IDLE
,它工作正常。
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')
时,我在comand提示符Error[2] no such file or directory
中看到错误。
当我刚刚使用with open('multip.txt', 'w')
时,它会变得i/o operation on closed file
问题出在哪里?
你可以这样尝试:
对于
No such file or directory
:with open(os.path.join(os.getcwd(),'outputs/multip.txt', 'w')) as ....:
2.对于错误I/O operation on closed file
:
def square(numbers):
with open(os.path.join(os.getcwd(),'outputs/multip.txt', 'w')) as f:
打开函数中的文件并对其执行操作
您应该使用如下所示的完整路径。
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")