将整数写入新文件

时间:2016-06-30 14:01:44

标签: python file file-writing

所以我试图打开一个新文件,并将n的所有值写入该文件。

for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
b = open('new', 'w')
b.write(n)

它将数字写为字符串,仅写入13,最后n

2 个答案:

答案 0 :(得分:1)

修改后的代码:

with open('new', 'w') as outfile:
    for n in [4, 7, 8, 10, 6, 3, 5, 13]:
        if n > 5:
            print(n)
            outfile.write(str(n))

或(不推荐)

for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
        b = open('new', 'a') # append mode
        b.write(str(n))
        b.close()

答案 1 :(得分:-1)

您只打印最后一个值。所以你只得到结果13.你必须在for循环中写入值。

b = open('new', 'w')
for n in [4, 7, 8, 10, 6, 3, 5, 13]:
    if n > 5:
        print(n)
        b.write(n)