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>Use the <code>csv</code> module to make it easier:</p>

<pre><code>import csv

data = [
    ['# Name Surname', 'Age', 'Class', 'Score','\n'],
    ['\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', 0]
]

# Remove all the ending new lines
data = [row[:-1] if row[-1] == '\n' else row for row in data]

# Write to file
with open('write_sublists.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(data)
</code></pre>

<h1>Discussion</h1>

<p>Your data is irregular: some row contains the ending new line, some row don't. Yet some row contains all strings and some row contains a mixed data type. The first step is to normalize them by remove all ending new lines. The <code>csv</code> module can take care of mixed data types just fine.</p>

python python-3.x