title: Made A Table In Python Beautiful Soup, How Do I Write It Neatly Into CSV?
body: <p>I am pretty new to python and webscraping, but I have managed to get a well working table to print, I am just curious how I would get this table into a CSV file in the exact same format as the print statement. Any logic explanations would be greatly appreciated and very helpful! My code is below...</p>
  <pre><code>from bs4 import BeautifulSoup
  import requests
  import time
  
  htmlText = requests.get('https://www.fangraphs.com/teams/mariners/stats').text
  soup = BeautifulSoup(htmlText, 'lxml', )
  playerTable = soup.find('div', class_='team-stats-table')
  
  
  def BattingStats():
      headers = [th.text for th in playerTable.find_all(&quot;th&quot;)]
      fmt_string = &quot; &quot;.join([&quot;{:&lt;25}&quot;, *[&quot;{:&lt;6}&quot;] * (len(headers) - 1)])
  
      print(fmt_string.format(*headers))
      for tr in playerTable.find_all(&quot;tr&quot;)[1:55]:
          tds = [td.text for td in tr.select(&quot;td&quot;)]
          with open('MarinersBattingStats.csv', 'w') as f:
              f.write(fmt_string.format(*tds))
              print(fmt_string.format(*tds))
  
  if __name__ == 'main':
      while True:
          BattingStats()
          timeWait = 100
          time.sleep(432 * timeWait)
  
  
  
  
  
  BattingStats()
  </code></pre>