title: Extracting the most common words and then append to a csv file with python
body: <p>So i'm trying to extract the most used words from a .txt file, and then put the 4 most common words into a csv file. (and then append if need be), At the moment it's extracting the most common words, and appending to a csv file. But it's appending each letter to a cell.</p>
  
  <p>python</p>
  
  <pre><code>import collections
  import pandas as pd
  import matplotlib.pyplot as plt
  import csv   
  fields=['first','second','third']
  
  
  # Read input file, note the encoding is specified here 
  # It may be different in your text file
  file = open('pyTest.txt', encoding="utf8")
  a= file.read()
  # Stopwords
  stopwords = set(line.strip() for line in open('stopwords.txt'))
  stopwords = stopwords.union(set(['mr','mrs','one','two','said']))
  # Instantiate a dictionary, and for every word in the file, 
  # Add to the dictionary if it doesn't exist. If it does, increase the count.
  wordcount = {}
  # To eliminate duplicates, remember to split by punctuation, and use case demiliters.
  for word in a.lower().split():
      word = word.replace(".","")
      word = word.replace(",","")
      word = word.replace(":","")
      word = word.replace("\"","")
      word = word.replace("!","")
      word = word.replace("â€œ","")
      word = word.replace("â€˜","")
      word = word.replace("*","")
      if word not in stopwords:
          if word not in wordcount:
              wordcount[word] = 1
          else:
              wordcount[word] += 1
  # Print most common word
  n_print = int(input("How many most common words to print: "))
  print("\nOK. The {} most common words are as follows\n".format(n_print))
  word_counter = collections.Counter(wordcount)
  for word in word_counter.most_common(n_print):
  
      print(word[0])
  
  # Close the file
  
  file.close()
  
  with open('old.csv', 'a') as out_file:
          writer = csv.writer(out_file)
          for word in word_counter.most_common(4):
              print(word)
              writer.writerow(word[0])
  </code></pre>
  
  <p>Output csv file</p>
  
  <pre><code>p,i,p,e
  
  d,i,a,m,e,t,e,r
  
  f,i,t,t,i,n,g,s
  
  o,u,t,s,i,d,e
  </code></pre>