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

时间:2019-06-17 07:45:53

标签: python list file-io

我有一个名为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'

1 个答案:

答案 0 :(得分:2)

您可以像这样格式化它:

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

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