Python 处理从列表写入新文件时出现语法错误
所以我想写一个程序,将10个随机数写入一个文本文件:Python 处理从列表写入新文件时出现语法错误,python,Python,所以我想写一个程序,将10个随机数写入一个文本文件: import random SIZE = 10 for i in range (0, SIZE, 1): y = random.randrange(0,100) x = open("data.txt","w+") x.write("\n") for i in range (0, SIZE, 1): x.write("Results: %d", %(y)) x.close() 我在“%(y)”中得到一个语法错误。但我不知
import random
SIZE = 10
for i in range (0, SIZE, 1):
y = random.randrange(0,100)
x = open("data.txt","w+")
x.write("\n")
for i in range (0, SIZE, 1):
x.write("Results: %d", %(y))
x.close()
我在“%(y)”中得到一个语法错误。但我不知道是什么原因造成的。问题是%是字符串之间使用的运算符,请参阅。这应该起作用:
import random
SIZE = 10
for i in range (0, SIZE, 1):
y = random.randrange(0,100)
x = open("data.txt","w+")
x.write("\n")
for i in range (0, SIZE, 1):
x.write("Results: %d" % y)
x.close()
另外,范围(0,大小,1)
可以替换为范围(大小)
,请参阅
您可以将语法与open(“data.txt”,“w+”)一起用作f
,这是根据的首选
另外,我不确定您在做什么,代码是否正确:
import random
SIZE = 10
with open("data.txt", "w+") as f:
f.write("\n")
for i in range(SIZE):
y = random.randrange(0, 100)
f.write("Results: %d" % y)
另外,请注意,
write
不会放任何换行符,可能您希望改为写“Results:%d\n”
。问题是%是字符串之间使用的运算符,请参阅。这应该起作用:
import random
SIZE = 10
for i in range (0, SIZE, 1):
y = random.randrange(0,100)
x = open("data.txt","w+")
x.write("\n")
for i in range (0, SIZE, 1):
x.write("Results: %d" % y)
x.close()
另外,范围(0,大小,1)
可以替换为范围(大小)
,请参阅
您可以将语法与open(“data.txt”,“w+”)一起用作f
,这是根据的首选
另外,我不确定您在做什么,代码是否正确:
import random
SIZE = 10
with open("data.txt", "w+") as f:
f.write("\n")
for i in range(SIZE):
y = random.randrange(0, 100)
f.write("Results: %d" % y)
另外,请注意,
write
不会添加任何换行符,也许您希望改为编写“Results:%d\n”
。这应该可以解决您的问题。这里的主要问题是%
符号使用不当,我还建议使用with
语句打开文件时进行一些代码编辑,以确保文件每次关闭,因此这是最佳做法
import random
SIZE = 10
with open("data.txt", 'w+') as x:
x.write("\n")
for i in range (0, SIZE, 1):
y = random.randrange(0,100)
x.write("Results: %d" % y)
这应该能解决你的问题。这里的主要问题是
%
符号使用不当,我还建议使用with
语句打开文件时进行一些代码编辑,以确保文件每次关闭,因此这是最佳做法
import random
SIZE = 10
with open("data.txt", 'w+') as x:
x.write("\n")
for i in range (0, SIZE, 1):
y = random.randrange(0,100)
x.write("Results: %d" % y)
省略逗号
x.write(“结果:%d”%y)
。省去逗号x.write(“结果:%d”%y)
。