将数字放在txt文件中

时间:2016-05-30 13:58:52

标签: python math

我试图把这些数字的输出放到一个文件中,但我失败了一点。 到目前为止,这是我的代码:

import os
import sys

with open('somefile.txt', 'rt') as f:
   print('Hello World!')
os.system("pause")

num = int(input("Display multiplication table of? "))

for i in range(1,1000001):
   print(num*i, file=f)

os.system("pause")

程序说= at file = f有一个语法错误。 Any1知道为什么吗?

1 个答案:

答案 0 :(得分:0)

你做错了两件事:

- Didn't have f defined when you wrote to the file - Didn't have the file opened as a write - you had it open as a read

修复它们后,代码执行得非常完美!

import os
import sys 
f = open('somefile.txt', 'wt') # CHANGED LINE
print('Hello World!')
os.system("pause")
num = int(input("Display multiplication table of? "))
for i in range(1,1000001):
   print(num*i, file=f)
os.system("pause")