title: How to format txt file in Python
body: <p>I am trying to convert a txt file into a csv file in Python. The current format of the txt file are several strings separated by spaces. I would like to write each string into one cell in the csv file.</p>
  
  <p>The txt file has got following structure:</p>
  
  <p>UserID Desktop Display (Version) (Server/Port handle), Date</p>
  
  <p>UserID Desktop Display (Version) (Server/Port handle), Date</p>
  
  <p>etc.</p>
  
  <p>My approach would be following:</p>
  
  <pre><code>with open('licfile.txt', "r+") as in_file:
      stripped = (line.strip() for line in in_file)
      lines = (line.split(" ") for line in stripped if line)
  
  with open('licfile.csv', 'w') as out_file:
      writer = csv.writer(out_file)
      writer.writerow(('user', 'desktop', 'display', 'version', 'server', 'handle', 'date'))
      writer.writerows(lines)
  </code></pre>
  
  <p>Unfortunately this is not working as expected. I do get following ValueError: I/O operation on closed file. Additionally only the intended row headers are shown in one cell in the csv file.</p>
  
  <p>Any tips on how to proceed? Many thanks in advance.</p>