Importing nested list into a text file
<p>I've been working on a problem which I realise I  am probably approaching the wrong way but am now confused and out of ideas. Any research that I have done has left me more confused, and thus I have come for help.</p>

<p>I have a nested list: </p>

<blockquote>
  <p>[['# Name Surname', 'Age', 'Class', 'Score', '\n'], ['name', '9', 'B',
  'N/A', '\n'], ['name1', '9', 'B', 'N/A', '\n'], ['name2', '8', 'B',
  'N/A', '\n'], ['name3', '9', 'B', 'N/A', '\n'], ['name4', '8', 'B',
  'N/A', '']]</p>
</blockquote>

<p>I am trying to make it so this list is imported into a text file in the correct layout. For this I flattened the string and then joined it together with ','. </p>

<p>The problem with this is that because the '\n' is being stored in the list itself, it adds a comma after this, which ends up turning this:</p>

<blockquote>
  <h1>Name Surname,Age,Class,Score,</h1>
  
  <p>Name,9,B,N/A,</p>
  
  <p>Name1,9,B,N/A,</p>
  
  <p>Name2,8,B,N/A,</p>
  
  <p>Name3,9,B,N/A,</p>
  
  <p>Name4,8,B,N/A,</p>
</blockquote>

<p>into:</p>

<blockquote>
  <h1>Name Surname,Age,Class,Score,</h1>
  
  <p>,</p>
  
  <p>,Name,9,B,N/A,</p>
  
  <p>,Name1,9,B,N/A,</p>
  
  <p>,Name2,8,B,N/A,</p>
  
  <p>,Name3,9,B,N/A,</p>
  
  <p>,Name4,8,B,N/A,</p>
</blockquote>

<p>If I remove the \n from the code the formatting in the text file is all wrong due to no new lines.</p>

<p>Is there a better way to approach this or is there a quick fix to all my problems that I cannot see?</p>

<p>Thanks!</p>

<p>My code for reference:</p>

<pre><code>def scorestore(score):

    user[accountLocation][3] = score


    file = ("classdata",schclass,".txt")
    file = "".join(file)

    flattened = [val for sublist in user for val in sublist]

    flatstring = ','.join(str(v) for v in flattened)



    accountlist = open(file,"w")

    accountlist.write(flatstring)

    accountlist.close()
</code></pre>

<p>Instead of making one string, how about writing lines. Use something like this:</p>

<pre><code> list_of_list = [[...]]
 lines = [','.join(line).strip() for line in list_of_list]
 lines = [line for line in lines if line]
 open(file,'w').writelines(lines)
</code></pre>

python python-3.x