如何在python中将带括号的列表打印到文件中

如何在python中将带括号的列表打印到文件中,python,Python,我正试图将我的输出列表打印到一个文件中,作为下面的输出,但它一直给我错误 样本输入 0 2 5 12 32 64 241 样本输入的position.dat的内容 [1, 0] [0, 2] [-4, -4] [-64, 0] [65536, 0] [4294967296, 0] [1329227995784915872903807060280344576, 1329227995784915872903807060280344576] 这是我的密码: infile = open("posit

我正试图将我的输出列表打印到一个文件中,作为下面的输出,但它一直给我错误

样本输入

0
2
5
12
32
64
241
样本输入的position.dat的内容

[1, 0]
[0, 2]
[-4, -4]
[-64, 0]
[65536, 0]
[4294967296, 0]
[1329227995784915872903807060280344576, 1329227995784915872903807060280344576]
这是我的密码:

infile = open("position.dat", "w")
def B(n):
    direction=[[1,0],[0,1],[-1,0],[0,-1]] #right, up, left, down
    start=[0,0]
    x=start[0]
    y=start[1]    
    if n>50000:
        return "Do not enter input that is larger than 50000"
    elif n==0:   #base case
        return [1, 0]
    elif n==1:
        return [1, 1]

    elif n%2==0 and n%4!=0:  #digit start from n=2 and every 4th n digit
        x=0            # start from second digit (n) x=0 for every 4th digit
        y=((-4)**(n//4))*2 


    elif n%4==0:      #print out every 4 digits n
        y=0  #every 4digit of y will be 0 start from n=0
        x=(-4)**(n//4)  #the pattern for every 4th digits

    elif n>3 and n%2 !=0 and n%4==1: #start from n=1 and for every 4th digit
        x=(-4)**(n//4)
        y=(-4)**(n//4)

    elif n%4==3 and n%2 != 0:  #start from n=3
        y=((-4)**(n//4))*2
        x=((-4)**(n//4))*-2
    return [int(x),int(y)]     #return result


print(B(0))    # print the input  onto python shell
print(B(2))
print(B(5))
print(B(12)) 
print(B(32))
print(B(64))
print(B(241))
print(B(1251))
#Please also input the integers below for printing it on the the file

infile.write(B(0)+'\n')   # these keep giving me error
infile.write(B(2)+'\n')   



infile.close()

可以将列表打印到带括号的文件上吗?

不能使用
write
直接写入列表。但是,您可以生成原始字符串:

s0 = "[" + ", ".join([str(x) for x in B(0)]) + "]"
infile.write(s0 + "\n")

您可以使用类似的方法:

with open ("temp.txt","wt") as fh:
   fh.write("%s\n" % str([0,1]))
  • 使用格式化原语
  • 明确地将元素转换为字符串
或者,使用个人格式:

fh.write("[%s]\n" %(','.join(map (str,B(0))))

列表
\uuuu str\uuu
方法可以为您执行此操作。使用

infile.write(str(B(0)) + '\n')
infile.write(str(B(2)) + '\n')   
“infle”对于您要写入的文件来说可能是一个容易混淆的名称