有人可以告诉我为什么当我打开这个 python 文件时它会自动关闭吗?
import itertools
for combination in itertools.product(xrange(10), repeat=4):
print ''.join(map(str, combination))
with open("C:\Users\User\Desktop\test.txt", "a") as myfile:
myfile.write(join(map(str, combination)))
固定缩进
那是因为您使用的是
with
风格打开文件。当您退出 with
块时,文件将关闭。这是打开文件的安全方式。这样你就不必在 close
上显式调用 myfile
方法。为了避免这种情况,你可以使用
myfile = open("C:\\Users\\User\\Desktop\\test.txt", "a")
myfile.write(join(map(str, combination)))
请注意,使用完该文件后,请确保使用
myfile.close()
您可以通过此页面了解详情
编辑
尝试使用这个
import itertools
with open(r"C:\Users\User\Desktop\test.txt", "a") as myfile:
for combination in itertools.product(range(10), repeat=4):
print (''.join(map(str, combination)))
myfile.write(''.join(map(str, combination)))
import itertools
for combination in itertools.product(xrange(10), repeat=4):
print ''.join(map(str, combination))
with open("C:\Users\User\Desktop\test.txt", "a") as myfile:
myfile.write(join(map(str, combination)))
现在就可以了。
with
会创建一个块,所以你需要缩进。请记住:)
您还应该将最后一行修改为:
myfile.write(''.join(map(str, combination)))
并参考@RetardedJoker的回答
这是我的代码:
import itertools
with open("C:\\Users\\User\\Desktop\\test.txt", "a") as myfile:
for combination in itertools.product(xrange(10), repeat=4):
result = ''.join(map(str, combination))
print result
myfile.write(result)
关于“with”命令:理解Python的“with”语句
简短描述:即使您忘记自己关闭文件,它们也会在块执行结束后关闭您的文件。这是一种更好的放置代码的方式,而不是 try-finally。
在您的情况下,它会为循环的每次迭代打开一次。并在最后关闭。然后,再次打开它进行下一次迭代。这效率很低。
只是一个建议,您希望避免在
for
循环中打开文件。
您可以在外部调用它,以便将其打开一次,然后运行循环。 with
语句将在块执行结束时自动关闭文件。但同样,取决于您的使用环境。
with open(r"C:\Users\User\Desktop\test.txt", "a") as myfile:
for combination in itertools.product(xrange(10), repeat=4):
print ''.join(map(str, combination))
myfile.write(''.join(map(str, combination)))
以下行添加一条提示,要求用户在退出脚本之前按 Enter 键。它使脚本保持运行,直到用户进行交互,从而允许您查看输出和结果。这是一个简单的方法希望有帮助。
input("Press Enter to exit...")