python - 如何摆脱数组中的内置引用并将其保存到文件中

标签 python file

我有一个像这样的二维数组:

  [["x","0xacc2d9"],
  ["y","0x56ae57"]]

我想保存这个数组,使其保留二维数组。 第一项有报价,第二项没有报价。

所以保存在文件中的结果应该是:

 [["x",0xacc2d9],
  ["y",0x56ae57]]

我尝试了各种方法,但由于引用不是额外的东西,而且是内置的,所以我无法删除它。 我已经尝试过。

lst. replace(""",")

另外,这个:

filename= 'test.txt'
 with open(filename, 'w') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerows(lst)

但它删除了 [] 、 "",我不想删除它们。

感谢您的帮助。

编辑2 由于某种原因,我需要我的输出有双引号不是单引号,因此输出必须是:which x has 双引号

   [["x",0xacc2d9],
      ["y",0x56ae57]]

最佳答案

并不完美,但它给了你一些可以玩的东西:

In [883]: lst =  [["x","0xacc2d9"], 
     ...:   ["y","0x56ae57"]]  
In [885]: with open('test.txt','w') as f: 
     ...:     f.write('[') 
     ...:     for row in lst: 
     ...:         f.write('[%r, %s]\n'%tuple(row)) 
     ...:     f.write(']\n') 
     ...:                                                                       
In [886]: cat test.txt                                                          
[['x', 0xacc2d9]
['y', 0x56ae57]
]

您打算如何使用此文件?

为了更清晰地处理括号(和引用替换):

In [887]: astr = '\n'.join(['[%r, %s]'%tuple(row) for row in lst])              
In [888]: astr                                                                  
Out[888]: "['x', 0xacc2d9]\n['y', 0x56ae57]"
In [895]: astr = astr.replace("'",'"')                                          
In [896]: astr                                                                  
Out[896]: '["x", 0xacc2d9]\n["y", 0x56ae57]'
In [897]: with open('test.txt','w') as f: 
     ...:     print('[%s]'%astr, file=f) 
     ...:                                                                       
In [898]: cat test.txt                                                          
[["x", 0xacc2d9]
["y", 0x56ae57]]

关于python - 如何摆脱数组中的内置引用并将其保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55446141/

相关文章:

python - os.path.exists 和 os.path.isfile 的区别?

file - 中间文件是不好的做法吗?

python - 当我调用 update_idletasks() 时,Tkinter 有时会卡住

java - 为什么我不能在java中更改所需文件的文件扩展名?

file - 你如何在 Go 中复制文件?

python - matplotlib:matshow 在图像顶部有网格线

c - 合并两个文件,为什么在末尾添加一个新行? C编程

python - QTreeview 更改行上的图标图标单击

python - 使用 Pandas 根据组内排名顺序创建新列

python - 如何使用 Python 访问 Windows Vista 上的文件属性?