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>The easiest way would probably be to remove the newlines from the sublists as you get them, the print each sublist one at a time. This would look something like:</p>

<pre><code>for sublist in users:
    print(",".join(val for val in sublist if not val.isspace()), file=accountlist)
</code></pre>

<p>This will fail on the 0 in your list, however. I'm not sure if you intend to handle that, or if it's extraneous. If you do need to handle is, then you'll have to change the generator expression to <code>str(val) for val in sublist if not str(val).isspace()</code>.</p>

python python-3.x