如何在没有括号的情况下将列表写入文件

How to write a list to a file without brackets

我有一个名为 LineValue 的整数列表,其形式为 [0, 1, 1, 2, 0, 0],我需要将其写入文件。为了防止我的代码出现读取错误,文件中的表格需要

0,1,1,2,0,0

相反,我得到的是

[0, 1, 1, 2, 0, 0]

当我尝试读取文件时,这会导致转换错误。我可以更改读取函数或写入函数,因为两者都是在单个导入模块中定义的,但我想我更愿意更改写入函数,其他条件相同。

编写代码:

def Write_Line(LineValue):
        with open("/usr/lib/cgi-bin/ClassValues/position","w") as f:  # Set index values for setup parameters
                f.write(str(LineValue))

阅读代码:

def Read_Line():
        with open("/usr/lib/cgi-bin/ClassValues/position","r") as f:  # Get index values for setup parameters
                LV = f.read()
        RetValue = [int(x) for x in LV.split(",")]
        return RetValue

错误:

Traceback (most recent call last):
  File "/usr/lib/cgi-bin/index.py", line 16, in <module>
    LineValue = read_Line()
  File "/usr/lib/cgi-bin/resource.py", line 14, in Read_Line
    RetValue = [int(x) for x in LV.split(",")]
  File "/usr/lib/cgi-bin/resource.py", line 14, in <listcomp>
    RetValue = [int(x) for x in LV.split(",")]
ValueError: invalid literal for int() with base 10: '[0'

你可以这样格式化:

>>> val = [0, 1, 1, 2, 0, 0]
>>> print(",".join(str(i) for i in val))
0,1,1,2,0,0
>>> 

当然,您可以调用 f.write 代替 print