-1

The csv file is like below:

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

I tried

with open('test.csv','r') as r, open('write.csv', 'w') as w:
    for line in r:
        line = line[1:-2]
        w.write(line + '\n')

but it outcomes

0,0,0
]
1,1
]
]

which should be:

0,0,0

1,1


That was weird for the empty list line, I have to do line[1:-3] to clean the line, but for the non-empty line with line[1:-2]

Here was how I wrote data into csv file:

list = [[0,0,0],[],[1,1],[],[]]

with open ('test.csv','a') as w:
    w = csv.writer(w, delimiter = '\n')
    w.writerow(list)
    w.close

heisthere
  • 324
  • 1
  • 10

2 Answers2

0

Use rstrip() and lstrip() to remove specific characters from the dns.

line = line.lstrip('[').rstrip(']\n ')

This removes the [ at the beginning and the ] and newline at the end.

Barmar
  • 596,455
  • 48
  • 393
  • 495
0

As mentioned, the problem is in the writing of the file in the first place. If this list only has a few base types (int, string, etc), you can use ast.literal_eval to build the list again

>>> import ast
>>> with open("test.csv") as f:
...     mylist = [ast.literal_eval(line) for line in f]
... 
>>> mylist
[[0, 0, 0], [], [1, 1], [], [], [0, 0, 0], [], [1, 1], [], []]
tdelaney
  • 55,698
  • 4
  • 59
  • 89