gooderp18绿色标准版
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

952 lines
89KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="csv — CSV File Reading and Writing" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/csv.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/csv.py The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to att..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Source code: Lib/csv.py The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to att..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>csv — CSV File Reading and Writing &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="configparser — Configuration file parser" href="configparser.html" />
  33. <link rel="prev" title="File Formats" href="fileformats.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/csv.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a><ul>
  86. <li><a class="reference internal" href="#module-contents">Module Contents</a></li>
  87. <li><a class="reference internal" href="#dialects-and-formatting-parameters">Dialects and Formatting Parameters</a></li>
  88. <li><a class="reference internal" href="#reader-objects">Reader Objects</a></li>
  89. <li><a class="reference internal" href="#writer-objects">Writer Objects</a></li>
  90. <li><a class="reference internal" href="#examples">Examples</a></li>
  91. </ul>
  92. </li>
  93. </ul>
  94. </div>
  95. <div>
  96. <h4>Previous topic</h4>
  97. <p class="topless"><a href="fileformats.html"
  98. title="previous chapter">File Formats</a></p>
  99. </div>
  100. <div>
  101. <h4>Next topic</h4>
  102. <p class="topless"><a href="configparser.html"
  103. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code> — Configuration file parser</a></p>
  104. </div>
  105. <div role="note" aria-label="source link">
  106. <h3>This Page</h3>
  107. <ul class="this-page-menu">
  108. <li><a href="../bugs.html">Report a Bug</a></li>
  109. <li>
  110. <a href="https://github.com/python/cpython/blob/main/Doc/library/csv.rst"
  111. rel="nofollow">Show Source
  112. </a>
  113. </li>
  114. </ul>
  115. </div>
  116. </nav>
  117. </div>
  118. </div>
  119. <div class="related" role="navigation" aria-label="related navigation">
  120. <h3>Navigation</h3>
  121. <ul>
  122. <li class="right" style="margin-right: 10px">
  123. <a href="../genindex.html" title="General Index"
  124. accesskey="I">index</a></li>
  125. <li class="right" >
  126. <a href="../py-modindex.html" title="Python Module Index"
  127. >modules</a> |</li>
  128. <li class="right" >
  129. <a href="configparser.html" title="configparser — Configuration file parser"
  130. accesskey="N">next</a> |</li>
  131. <li class="right" >
  132. <a href="fileformats.html" title="File Formats"
  133. accesskey="P">previous</a> |</li>
  134. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  135. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  136. <li class="switchers">
  137. <div class="language_switcher_placeholder"></div>
  138. <div class="version_switcher_placeholder"></div>
  139. </li>
  140. <li>
  141. </li>
  142. <li id="cpython-language-and-version">
  143. <a href="../index.html">3.12.3 Documentation</a> &#187;
  144. </li>
  145. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  146. <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">File Formats</a> &#187;</li>
  147. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a></li>
  148. <li class="right">
  149. <div class="inline-search" role="search">
  150. <form class="inline-search" action="../search.html" method="get">
  151. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  152. <input type="submit" value="Go" />
  153. </form>
  154. </div>
  155. |
  156. </li>
  157. <li class="right">
  158. <label class="theme-selector-label">
  159. Theme
  160. <select class="theme-selector" oninput="activateTheme(this.value)">
  161. <option value="auto" selected>Auto</option>
  162. <option value="light">Light</option>
  163. <option value="dark">Dark</option>
  164. </select>
  165. </label> |</li>
  166. </ul>
  167. </div>
  168. <div class="document">
  169. <div class="documentwrapper">
  170. <div class="bodywrapper">
  171. <div class="body" role="main">
  172. <section id="module-csv">
  173. <span id="csv-csv-file-reading-and-writing"></span><h1><a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> — CSV File Reading and Writing<a class="headerlink" href="#module-csv" title="Link to this heading">¶</a></h1>
  174. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/csv.py">Lib/csv.py</a></p>
  175. <hr class="docutils" id="index-0" />
  176. <p>The so-called CSV (Comma Separated Values) format is the most common import and
  177. export format for spreadsheets and databases. CSV format was used for many
  178. years prior to attempts to describe the format in a standardized way in
  179. <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4180.html"><strong>RFC 4180</strong></a>. The lack of a well-defined standard means that subtle differences
  180. often exist in the data produced and consumed by different applications. These
  181. differences can make it annoying to process CSV files from multiple sources.
  182. Still, while the delimiters and quoting characters vary, the overall format is
  183. similar enough that it is possible to write a single module which can
  184. efficiently manipulate such data, hiding the details of reading and writing the
  185. data from the programmer.</p>
  186. <p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module implements classes to read and write tabular data in CSV
  187. format. It allows programmers to say, “write this data in the format preferred
  188. by Excel,” or “read data from this file which was generated by Excel,” without
  189. knowing the precise details of the CSV format used by Excel. Programmers can
  190. also describe the CSV formats understood by other applications or define their
  191. own special-purpose CSV formats.</p>
  192. <p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module’s <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> and <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects read and
  193. write sequences. Programmers can also read and write data in dictionary form
  194. using the <a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> and <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> classes.</p>
  195. <div class="admonition seealso">
  196. <p class="admonition-title">See also</p>
  197. <dl class="simple">
  198. <dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0305/"><strong>PEP 305</strong></a> - CSV File API</dt><dd><p>The Python Enhancement Proposal which proposed this addition to Python.</p>
  199. </dd>
  200. </dl>
  201. </div>
  202. <section id="module-contents">
  203. <span id="csv-contents"></span><h2>Module Contents<a class="headerlink" href="#module-contents" title="Link to this heading">¶</a></h2>
  204. <p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following functions:</p>
  205. <dl class="py function" id="index-3">
  206. <dt class="sig sig-object py" id="csv.reader">
  207. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">reader</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">csvfile</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">fmtparams</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.reader" title="Link to this definition">¶</a></dt>
  208. <dd><p>Return a <a class="reference internal" href="#reader-objects"><span class="std std-ref">reader object</span></a> that will process
  209. lines from the given <em>csvfile</em>. A csvfile must be an iterable of
  210. strings, each in the reader’s defined csv format.
  211. A csvfile is most commonly a file-like object or list.
  212. If <em>csvfile</em> is a file object,
  213. it should be opened with <code class="docutils literal notranslate"><span class="pre">newline=''</span></code>. <a class="footnote-reference brackets" href="#id4" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a> An optional
  214. <em>dialect</em> parameter can be given which is used to define a set of parameters
  215. specific to a particular CSV dialect. It may be an instance of a subclass of
  216. the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class or one of the strings returned by the
  217. <a class="reference internal" href="#csv.list_dialects" title="csv.list_dialects"><code class="xref py py-func docutils literal notranslate"><span class="pre">list_dialects()</span></code></a> function. The other optional <em>fmtparams</em> keyword arguments
  218. can be given to override individual formatting parameters in the current
  219. dialect. For full details about the dialect and formatting parameters, see
  220. section <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a>.</p>
  221. <p>Each row read from the csv file is returned as a list of strings. No
  222. automatic data type conversion is performed unless the <code class="docutils literal notranslate"><span class="pre">QUOTE_NONNUMERIC</span></code> format
  223. option is specified (in which case unquoted fields are transformed into floats).</p>
  224. <p>A short usage example:</p>
  225. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">csv</span>
  226. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;eggs.csv&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  227. <span class="gp">... </span> <span class="n">spamreader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="n">quotechar</span><span class="o">=</span><span class="s1">&#39;|&#39;</span><span class="p">)</span>
  228. <span class="gp">... </span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">spamreader</span><span class="p">:</span>
  229. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;, &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">row</span><span class="p">))</span>
  230. <span class="go">Spam, Spam, Spam, Spam, Spam, Baked Beans</span>
  231. <span class="go">Spam, Lovely Spam, Wonderful Spam</span>
  232. </pre></div>
  233. </div>
  234. </dd></dl>
  235. <dl class="py function">
  236. <dt class="sig sig-object py" id="csv.writer">
  237. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">writer</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">csvfile</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">fmtparams</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.writer" title="Link to this definition">¶</a></dt>
  238. <dd><p>Return a writer object responsible for converting the user’s data into delimited
  239. strings on the given file-like object. <em>csvfile</em> can be any object with a
  240. <a class="reference internal" href="io.html#io.TextIOBase.write" title="io.TextIOBase.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method. If <em>csvfile</em> is a file object, it should be opened with
  241. <code class="docutils literal notranslate"><span class="pre">newline=''</span></code> <a class="footnote-reference brackets" href="#id4" id="id2" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>. An optional <em>dialect</em>
  242. parameter can be given which is used to define a set of parameters specific to a
  243. particular CSV dialect. It may be an instance of a subclass of the
  244. <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class or one of the strings returned by the
  245. <a class="reference internal" href="#csv.list_dialects" title="csv.list_dialects"><code class="xref py py-func docutils literal notranslate"><span class="pre">list_dialects()</span></code></a> function. The other optional <em>fmtparams</em> keyword arguments
  246. can be given to override individual formatting parameters in the current
  247. dialect. For full details about dialects and formatting parameters, see
  248. the <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a> section. To make it
  249. as easy as possible to interface with modules which implement the DB API, the
  250. value <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is written as the empty string. While this isn’t a
  251. reversible transformation, it makes it easier to dump SQL NULL data values to
  252. CSV files without preprocessing the data returned from a <code class="docutils literal notranslate"><span class="pre">cursor.fetch*</span></code> call.
  253. All other non-string data are stringified with <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> before being written.</p>
  254. <p>A short usage example:</p>
  255. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  256. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;eggs.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  257. <span class="n">spamwriter</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span>
  258. <span class="n">quotechar</span><span class="o">=</span><span class="s1">&#39;|&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_MINIMAL</span><span class="p">)</span>
  259. <span class="n">spamwriter</span><span class="o">.</span><span class="n">writerow</span><span class="p">([</span><span class="s1">&#39;Spam&#39;</span><span class="p">]</span> <span class="o">*</span> <span class="mi">5</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;Baked Beans&#39;</span><span class="p">])</span>
  260. <span class="n">spamwriter</span><span class="o">.</span><span class="n">writerow</span><span class="p">([</span><span class="s1">&#39;Spam&#39;</span><span class="p">,</span> <span class="s1">&#39;Lovely Spam&#39;</span><span class="p">,</span> <span class="s1">&#39;Wonderful Spam&#39;</span><span class="p">])</span>
  261. </pre></div>
  262. </div>
  263. </dd></dl>
  264. <dl class="py function">
  265. <dt class="sig sig-object py" id="csv.register_dialect">
  266. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">register_dialect</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">dialect</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">**fmtparams</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.register_dialect" title="Link to this definition">¶</a></dt>
  267. <dd><p>Associate <em>dialect</em> with <em>name</em>. <em>name</em> must be a string. The
  268. dialect can be specified either by passing a sub-class of <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>, or
  269. by <em>fmtparams</em> keyword arguments, or both, with keyword arguments overriding
  270. parameters of the dialect. For full details about dialects and formatting
  271. parameters, see section <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a>.</p>
  272. </dd></dl>
  273. <dl class="py function">
  274. <dt class="sig sig-object py" id="csv.unregister_dialect">
  275. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">unregister_dialect</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.unregister_dialect" title="Link to this definition">¶</a></dt>
  276. <dd><p>Delete the dialect associated with <em>name</em> from the dialect registry. An
  277. <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if <em>name</em> is not a registered dialect name.</p>
  278. </dd></dl>
  279. <dl class="py function">
  280. <dt class="sig sig-object py" id="csv.get_dialect">
  281. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">get_dialect</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.get_dialect" title="Link to this definition">¶</a></dt>
  282. <dd><p>Return the dialect associated with <em>name</em>. An <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if
  283. <em>name</em> is not a registered dialect name. This function returns an immutable
  284. <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>.</p>
  285. </dd></dl>
  286. <dl class="py function">
  287. <dt class="sig sig-object py" id="csv.list_dialects">
  288. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">list_dialects</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.list_dialects" title="Link to this definition">¶</a></dt>
  289. <dd><p>Return the names of all registered dialects.</p>
  290. </dd></dl>
  291. <dl class="py function">
  292. <dt class="sig sig-object py" id="csv.field_size_limit">
  293. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">field_size_limit</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">new_limit</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.field_size_limit" title="Link to this definition">¶</a></dt>
  294. <dd><p>Returns the current maximum field size allowed by the parser. If <em>new_limit</em> is
  295. given, this becomes the new limit.</p>
  296. </dd></dl>
  297. <p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following classes:</p>
  298. <dl class="py class">
  299. <dt class="sig sig-object py" id="csv.DictReader">
  300. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">DictReader</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">f</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fieldnames</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">restkey</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">restval</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictReader" title="Link to this definition">¶</a></dt>
  301. <dd><p>Create an object that operates like a regular reader but maps the
  302. information in each row to a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> whose keys are given by the
  303. optional <em>fieldnames</em> parameter.</p>
  304. <p>The <em>fieldnames</em> parameter is a <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a>. If <em>fieldnames</em> is
  305. omitted, the values in the first row of file <em>f</em> will be used as the
  306. fieldnames. Regardless of how the fieldnames are determined, the
  307. dictionary preserves their original ordering.</p>
  308. <p>If a row has more fields than fieldnames, the remaining data is put in a
  309. list and stored with the fieldname specified by <em>restkey</em> (which defaults
  310. to <code class="docutils literal notranslate"><span class="pre">None</span></code>). If a non-blank row has fewer fields than fieldnames, the
  311. missing values are filled-in with the value of <em>restval</em> (which defaults
  312. to <code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
  313. <p>All other optional or keyword arguments are passed to the underlying
  314. <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> instance.</p>
  315. <p>If the argument passed to <em>fieldnames</em> is an iterator, it will be coerced to a <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>.</p>
  316. <div class="versionchanged">
  317. <p><span class="versionmodified changed">Changed in version 3.6: </span>Returned rows are now of type <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code>.</p>
  318. </div>
  319. <div class="versionchanged">
  320. <p><span class="versionmodified changed">Changed in version 3.8: </span>Returned rows are now of type <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p>
  321. </div>
  322. <p>A short usage example:</p>
  323. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">csv</span>
  324. <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;names.csv&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  325. <span class="gp">... </span> <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">DictReader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">)</span>
  326. <span class="gp">... </span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  327. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="s1">&#39;first_name&#39;</span><span class="p">],</span> <span class="n">row</span><span class="p">[</span><span class="s1">&#39;last_name&#39;</span><span class="p">])</span>
  328. <span class="gp">...</span>
  329. <span class="go">Eric Idle</span>
  330. <span class="go">John Cleese</span>
  331. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  332. <span class="go">{&#39;first_name&#39;: &#39;John&#39;, &#39;last_name&#39;: &#39;Cleese&#39;}</span>
  333. </pre></div>
  334. </div>
  335. </dd></dl>
  336. <dl class="py class">
  337. <dt class="sig sig-object py" id="csv.DictWriter">
  338. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">DictWriter</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">f</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fieldnames</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">restval</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">extrasaction</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'raise'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictWriter" title="Link to this definition">¶</a></dt>
  339. <dd><p>Create an object which operates like a regular writer but maps dictionaries
  340. onto output rows. The <em>fieldnames</em> parameter is a <a class="reference internal" href="collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sequence</span></code></a> of keys that identify the order in which values in the
  341. dictionary passed to the <a class="reference internal" href="#csv.csvwriter.writerow" title="csv.csvwriter.writerow"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writerow()</span></code></a> method are written to file
  342. <em>f</em>. The optional <em>restval</em> parameter specifies the value to be
  343. written if the dictionary is missing a key in <em>fieldnames</em>. If the
  344. dictionary passed to the <a class="reference internal" href="#csv.csvwriter.writerow" title="csv.csvwriter.writerow"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writerow()</span></code></a> method contains a key not found in
  345. <em>fieldnames</em>, the optional <em>extrasaction</em> parameter indicates what action to
  346. take.
  347. If it is set to <code class="docutils literal notranslate"><span class="pre">'raise'</span></code>, the default value, a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
  348. is raised.
  349. If it is set to <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, extra values in the dictionary are ignored.
  350. Any other optional or keyword arguments are passed to the underlying
  351. <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> instance.</p>
  352. <p>Note that unlike the <a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> class, the <em>fieldnames</em> parameter
  353. of the <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> class is not optional.</p>
  354. <p>If the argument passed to <em>fieldnames</em> is an iterator, it will be coerced to a <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>.</p>
  355. <p>A short usage example:</p>
  356. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  357. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;names.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  358. <span class="n">fieldnames</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;first_name&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">]</span>
  359. <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">DictWriter</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">fieldnames</span><span class="o">=</span><span class="n">fieldnames</span><span class="p">)</span>
  360. <span class="n">writer</span><span class="o">.</span><span class="n">writeheader</span><span class="p">()</span>
  361. <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Baked&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Beans&#39;</span><span class="p">})</span>
  362. <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Lovely&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Spam&#39;</span><span class="p">})</span>
  363. <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Wonderful&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Spam&#39;</span><span class="p">})</span>
  364. </pre></div>
  365. </div>
  366. </dd></dl>
  367. <dl class="py class">
  368. <dt class="sig sig-object py" id="csv.Dialect">
  369. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Dialect</span></span><a class="headerlink" href="#csv.Dialect" title="Link to this definition">¶</a></dt>
  370. <dd><p>The <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class is a container class whose attributes contain
  371. information for how to handle doublequotes, whitespace, delimiters, etc.
  372. Due to the lack of a strict CSV specification, different applications
  373. produce subtly different CSV data. <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> instances define how
  374. <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> and <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> instances behave.</p>
  375. <p>All available <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> names are returned by <a class="reference internal" href="#csv.list_dialects" title="csv.list_dialects"><code class="xref py py-func docutils literal notranslate"><span class="pre">list_dialects()</span></code></a>,
  376. and they can be registered with specific <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> and <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a>
  377. classes through their initializer (<code class="docutils literal notranslate"><span class="pre">__init__</span></code>) functions like this:</p>
  378. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  379. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;students.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  380. <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="s1">&#39;unix&#39;</span><span class="p">)</span>
  381. </pre></div>
  382. </div>
  383. </dd></dl>
  384. <dl class="py class">
  385. <dt class="sig sig-object py" id="csv.excel">
  386. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">excel</span></span><a class="headerlink" href="#csv.excel" title="Link to this definition">¶</a></dt>
  387. <dd><p>The <a class="reference internal" href="#csv.excel" title="csv.excel"><code class="xref py py-class docutils literal notranslate"><span class="pre">excel</span></code></a> class defines the usual properties of an Excel-generated CSV
  388. file. It is registered with the dialect name <code class="docutils literal notranslate"><span class="pre">'excel'</span></code>.</p>
  389. </dd></dl>
  390. <dl class="py class">
  391. <dt class="sig sig-object py" id="csv.excel_tab">
  392. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">excel_tab</span></span><a class="headerlink" href="#csv.excel_tab" title="Link to this definition">¶</a></dt>
  393. <dd><p>The <a class="reference internal" href="#csv.excel_tab" title="csv.excel_tab"><code class="xref py py-class docutils literal notranslate"><span class="pre">excel_tab</span></code></a> class defines the usual properties of an Excel-generated
  394. TAB-delimited file. It is registered with the dialect name <code class="docutils literal notranslate"><span class="pre">'excel-tab'</span></code>.</p>
  395. </dd></dl>
  396. <dl class="py class">
  397. <dt class="sig sig-object py" id="csv.unix_dialect">
  398. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">unix_dialect</span></span><a class="headerlink" href="#csv.unix_dialect" title="Link to this definition">¶</a></dt>
  399. <dd><p>The <a class="reference internal" href="#csv.unix_dialect" title="csv.unix_dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">unix_dialect</span></code></a> class defines the usual properties of a CSV file
  400. generated on UNIX systems, i.e. using <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> as line terminator and quoting
  401. all fields. It is registered with the dialect name <code class="docutils literal notranslate"><span class="pre">'unix'</span></code>.</p>
  402. <div class="versionadded">
  403. <p><span class="versionmodified added">New in version 3.2.</span></p>
  404. </div>
  405. </dd></dl>
  406. <dl class="py class">
  407. <dt class="sig sig-object py" id="csv.Sniffer">
  408. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Sniffer</span></span><a class="headerlink" href="#csv.Sniffer" title="Link to this definition">¶</a></dt>
  409. <dd><p>The <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> class is used to deduce the format of a CSV file.</p>
  410. <p>The <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> class provides two methods:</p>
  411. <dl class="py method">
  412. <dt class="sig sig-object py" id="csv.Sniffer.sniff">
  413. <span class="sig-name descname"><span class="pre">sniff</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">sample</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">delimiters</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.Sniffer.sniff" title="Link to this definition">¶</a></dt>
  414. <dd><p>Analyze the given <em>sample</em> and return a <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> subclass
  415. reflecting the parameters found. If the optional <em>delimiters</em> parameter
  416. is given, it is interpreted as a string containing possible valid
  417. delimiter characters.</p>
  418. </dd></dl>
  419. <dl class="py method">
  420. <dt class="sig sig-object py" id="csv.Sniffer.has_header">
  421. <span class="sig-name descname"><span class="pre">has_header</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">sample</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.Sniffer.has_header" title="Link to this definition">¶</a></dt>
  422. <dd><p>Analyze the sample text (presumed to be in CSV format) and return
  423. <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the first row appears to be a series of column headers.
  424. Inspecting each column, one of two key criteria will be considered to
  425. estimate if the sample contains a header:</p>
  426. <ul class="simple">
  427. <li><p>the second through n-th rows contain numeric values</p></li>
  428. <li><p>the second through n-th rows contain strings where at least one value’s
  429. length differs from that of the putative header of that column.</p></li>
  430. </ul>
  431. <p>Twenty rows after the first row are sampled; if more than half of columns +
  432. rows meet the criteria, <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> is returned.</p>
  433. </dd></dl>
  434. <div class="admonition note">
  435. <p class="admonition-title">Note</p>
  436. <p>This method is a rough heuristic and may produce both false positives and
  437. negatives.</p>
  438. </div>
  439. </dd></dl>
  440. <p>An example for <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> use:</p>
  441. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;example.csv&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
  442. <span class="n">dialect</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">Sniffer</span><span class="p">()</span><span class="o">.</span><span class="n">sniff</span><span class="p">(</span><span class="n">csvfile</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1024</span><span class="p">))</span>
  443. <span class="n">csvfile</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  444. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">dialect</span><span class="p">)</span>
  445. <span class="c1"># ... process CSV file contents here ...</span>
  446. </pre></div>
  447. </div>
  448. <p id="csv-constants">The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following constants:</p>
  449. <dl class="py data">
  450. <dt class="sig sig-object py" id="csv.QUOTE_ALL">
  451. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_ALL</span></span><a class="headerlink" href="#csv.QUOTE_ALL" title="Link to this definition">¶</a></dt>
  452. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to quote all fields.</p>
  453. </dd></dl>
  454. <dl class="py data">
  455. <dt class="sig sig-object py" id="csv.QUOTE_MINIMAL">
  456. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_MINIMAL</span></span><a class="headerlink" href="#csv.QUOTE_MINIMAL" title="Link to this definition">¶</a></dt>
  457. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to only quote those fields which contain
  458. special characters such as <em>delimiter</em>, <em>quotechar</em> or any of the characters in
  459. <em>lineterminator</em>.</p>
  460. </dd></dl>
  461. <dl class="py data">
  462. <dt class="sig sig-object py" id="csv.QUOTE_NONNUMERIC">
  463. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_NONNUMERIC</span></span><a class="headerlink" href="#csv.QUOTE_NONNUMERIC" title="Link to this definition">¶</a></dt>
  464. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to quote all non-numeric fields.</p>
  465. <p>Instructs <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> objects to convert all non-quoted fields to type <em>float</em>.</p>
  466. </dd></dl>
  467. <dl class="py data">
  468. <dt class="sig sig-object py" id="csv.QUOTE_NONE">
  469. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_NONE</span></span><a class="headerlink" href="#csv.QUOTE_NONE" title="Link to this definition">¶</a></dt>
  470. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to never quote fields. When the current
  471. <em>delimiter</em> occurs in output data it is preceded by the current <em>escapechar</em>
  472. character. If <em>escapechar</em> is not set, the writer will raise <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> if
  473. any characters that require escaping are encountered.</p>
  474. <p>Instructs <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> objects to perform no special processing of quote characters.</p>
  475. </dd></dl>
  476. <dl class="py data">
  477. <dt class="sig sig-object py" id="csv.QUOTE_NOTNULL">
  478. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_NOTNULL</span></span><a class="headerlink" href="#csv.QUOTE_NOTNULL" title="Link to this definition">¶</a></dt>
  479. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to quote all fields which are not
  480. <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is similar to <a class="reference internal" href="#csv.QUOTE_ALL" title="csv.QUOTE_ALL"><code class="xref py py-data docutils literal notranslate"><span class="pre">QUOTE_ALL</span></code></a>, except that if a
  481. field value is <code class="docutils literal notranslate"><span class="pre">None</span></code> an empty (unquoted) string is written.</p>
  482. <p>Instructs <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> objects to interpret an empty (unquoted) field as None and
  483. to otherwise behave as <a class="reference internal" href="#csv.QUOTE_ALL" title="csv.QUOTE_ALL"><code class="xref py py-data docutils literal notranslate"><span class="pre">QUOTE_ALL</span></code></a>.</p>
  484. <div class="versionadded">
  485. <p><span class="versionmodified added">New in version 3.12.</span></p>
  486. </div>
  487. </dd></dl>
  488. <dl class="py data">
  489. <dt class="sig sig-object py" id="csv.QUOTE_STRINGS">
  490. <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_STRINGS</span></span><a class="headerlink" href="#csv.QUOTE_STRINGS" title="Link to this definition">¶</a></dt>
  491. <dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to always place quotes around fields
  492. which are strings. This is similar to <a class="reference internal" href="#csv.QUOTE_NONNUMERIC" title="csv.QUOTE_NONNUMERIC"><code class="xref py py-data docutils literal notranslate"><span class="pre">QUOTE_NONNUMERIC</span></code></a>, except that if a
  493. field value is <code class="docutils literal notranslate"><span class="pre">None</span></code> an empty (unquoted) string is written.</p>
  494. <p>Instructs <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> objects to interpret an empty (unquoted) string as <code class="docutils literal notranslate"><span class="pre">None</span></code> and
  495. to otherwise behave as <a class="reference internal" href="#csv.QUOTE_NONNUMERIC" title="csv.QUOTE_NONNUMERIC"><code class="xref py py-data docutils literal notranslate"><span class="pre">QUOTE_NONNUMERIC</span></code></a>.</p>
  496. <div class="versionadded">
  497. <p><span class="versionmodified added">New in version 3.12.</span></p>
  498. </div>
  499. </dd></dl>
  500. <p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following exception:</p>
  501. <dl class="py exception">
  502. <dt class="sig sig-object py" id="csv.Error">
  503. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Error</span></span><a class="headerlink" href="#csv.Error" title="Link to this definition">¶</a></dt>
  504. <dd><p>Raised by any of the functions when an error is detected.</p>
  505. </dd></dl>
  506. </section>
  507. <section id="dialects-and-formatting-parameters">
  508. <span id="csv-fmt-params"></span><h2>Dialects and Formatting Parameters<a class="headerlink" href="#dialects-and-formatting-parameters" title="Link to this heading">¶</a></h2>
  509. <p>To make it easier to specify the format of input and output records, specific
  510. formatting parameters are grouped together into dialects. A dialect is a
  511. subclass of the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class containing various attributes
  512. describing the format of the CSV file. When creating <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> or
  513. <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects, the programmer can specify a string or a subclass of
  514. the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class as the dialect parameter. In addition to, or instead
  515. of, the <em>dialect</em> parameter, the programmer can also specify individual
  516. formatting parameters, which have the same names as the attributes defined below
  517. for the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class.</p>
  518. <p>Dialects support the following attributes:</p>
  519. <dl class="py attribute">
  520. <dt class="sig sig-object py" id="csv.Dialect.delimiter">
  521. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">delimiter</span></span><a class="headerlink" href="#csv.Dialect.delimiter" title="Link to this definition">¶</a></dt>
  522. <dd><p>A one-character string used to separate fields. It defaults to <code class="docutils literal notranslate"><span class="pre">','</span></code>.</p>
  523. </dd></dl>
  524. <dl class="py attribute">
  525. <dt class="sig sig-object py" id="csv.Dialect.doublequote">
  526. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">doublequote</span></span><a class="headerlink" href="#csv.Dialect.doublequote" title="Link to this definition">¶</a></dt>
  527. <dd><p>Controls how instances of <em>quotechar</em> appearing inside a field should
  528. themselves be quoted. When <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, the character is doubled. When
  529. <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, the <em>escapechar</em> is used as a prefix to the <em>quotechar</em>. It
  530. defaults to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
  531. <p>On output, if <em>doublequote</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> and no <em>escapechar</em> is set,
  532. <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if a <em>quotechar</em> is found in a field.</p>
  533. </dd></dl>
  534. <dl class="py attribute">
  535. <dt class="sig sig-object py" id="csv.Dialect.escapechar">
  536. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">escapechar</span></span><a class="headerlink" href="#csv.Dialect.escapechar" title="Link to this definition">¶</a></dt>
  537. <dd><p>A one-character string used by the writer to escape the <em>delimiter</em> if <em>quoting</em>
  538. is set to <a class="reference internal" href="#csv.QUOTE_NONE" title="csv.QUOTE_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">QUOTE_NONE</span></code></a> and the <em>quotechar</em> if <em>doublequote</em> is
  539. <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. On reading, the <em>escapechar</em> removes any special meaning from
  540. the following character. It defaults to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, which disables escaping.</p>
  541. <div class="versionchanged">
  542. <p><span class="versionmodified changed">Changed in version 3.11: </span>An empty <em>escapechar</em> is not allowed.</p>
  543. </div>
  544. </dd></dl>
  545. <dl class="py attribute">
  546. <dt class="sig sig-object py" id="csv.Dialect.lineterminator">
  547. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">lineterminator</span></span><a class="headerlink" href="#csv.Dialect.lineterminator" title="Link to this definition">¶</a></dt>
  548. <dd><p>The string used to terminate lines produced by the <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a>. It defaults
  549. to <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>.</p>
  550. <div class="admonition note">
  551. <p class="admonition-title">Note</p>
  552. <p>The <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> is hard-coded to recognise either <code class="docutils literal notranslate"><span class="pre">'\r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> as
  553. end-of-line, and ignores <em>lineterminator</em>. This behavior may change in the
  554. future.</p>
  555. </div>
  556. </dd></dl>
  557. <dl class="py attribute">
  558. <dt class="sig sig-object py" id="csv.Dialect.quotechar">
  559. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">quotechar</span></span><a class="headerlink" href="#csv.Dialect.quotechar" title="Link to this definition">¶</a></dt>
  560. <dd><p>A one-character string used to quote fields containing special characters, such
  561. as the <em>delimiter</em> or <em>quotechar</em>, or which contain new-line characters. It
  562. defaults to <code class="docutils literal notranslate"><span class="pre">'&quot;'</span></code>.</p>
  563. <div class="versionchanged">
  564. <p><span class="versionmodified changed">Changed in version 3.11: </span>An empty <em>quotechar</em> is not allowed.</p>
  565. </div>
  566. </dd></dl>
  567. <dl class="py attribute">
  568. <dt class="sig sig-object py" id="csv.Dialect.quoting">
  569. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">quoting</span></span><a class="headerlink" href="#csv.Dialect.quoting" title="Link to this definition">¶</a></dt>
  570. <dd><p>Controls when quotes should be generated by the writer and recognised by the
  571. reader. It can take on any of the <a class="reference internal" href="#csv-constants"><span class="std std-ref">QUOTE_* constants</span></a>
  572. and defaults to <a class="reference internal" href="#csv.QUOTE_MINIMAL" title="csv.QUOTE_MINIMAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">QUOTE_MINIMAL</span></code></a>.</p>
  573. </dd></dl>
  574. <dl class="py attribute">
  575. <dt class="sig sig-object py" id="csv.Dialect.skipinitialspace">
  576. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">skipinitialspace</span></span><a class="headerlink" href="#csv.Dialect.skipinitialspace" title="Link to this definition">¶</a></dt>
  577. <dd><p>When <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, spaces immediately following the <em>delimiter</em> are ignored.
  578. The default is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
  579. </dd></dl>
  580. <dl class="py attribute">
  581. <dt class="sig sig-object py" id="csv.Dialect.strict">
  582. <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">strict</span></span><a class="headerlink" href="#csv.Dialect.strict" title="Link to this definition">¶</a></dt>
  583. <dd><p>When <code class="docutils literal notranslate"><span class="pre">True</span></code>, raise exception <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> on bad CSV input.
  584. The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
  585. </dd></dl>
  586. </section>
  587. <section id="reader-objects">
  588. <span id="id3"></span><h2>Reader Objects<a class="headerlink" href="#reader-objects" title="Link to this heading">¶</a></h2>
  589. <p>Reader objects (<a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> instances and objects returned by the
  590. <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-func docutils literal notranslate"><span class="pre">reader()</span></code></a> function) have the following public methods:</p>
  591. <dl class="py method">
  592. <dt class="sig sig-object py" id="csv.csvreader.__next__">
  593. <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">__next__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvreader.__next__" title="Link to this definition">¶</a></dt>
  594. <dd><p>Return the next row of the reader’s iterable object as a list (if the object
  595. was returned from <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-func docutils literal notranslate"><span class="pre">reader()</span></code></a>) or a dict (if it is a <a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a>
  596. instance), parsed according to the current <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>. Usually you
  597. should call this as <code class="docutils literal notranslate"><span class="pre">next(reader)</span></code>.</p>
  598. </dd></dl>
  599. <p>Reader objects have the following public attributes:</p>
  600. <dl class="py attribute">
  601. <dt class="sig sig-object py" id="csv.csvreader.dialect">
  602. <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">dialect</span></span><a class="headerlink" href="#csv.csvreader.dialect" title="Link to this definition">¶</a></dt>
  603. <dd><p>A read-only description of the dialect in use by the parser.</p>
  604. </dd></dl>
  605. <dl class="py attribute">
  606. <dt class="sig sig-object py" id="csv.csvreader.line_num">
  607. <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">line_num</span></span><a class="headerlink" href="#csv.csvreader.line_num" title="Link to this definition">¶</a></dt>
  608. <dd><p>The number of lines read from the source iterator. This is not the same as the
  609. number of records returned, as records can span multiple lines.</p>
  610. </dd></dl>
  611. <p>DictReader objects have the following public attribute:</p>
  612. <dl class="py attribute">
  613. <dt class="sig sig-object py" id="csv.DictReader.fieldnames">
  614. <span class="sig-prename descclassname"><span class="pre">DictReader.</span></span><span class="sig-name descname"><span class="pre">fieldnames</span></span><a class="headerlink" href="#csv.DictReader.fieldnames" title="Link to this definition">¶</a></dt>
  615. <dd><p>If not passed as a parameter when creating the object, this attribute is
  616. initialized upon first access or when the first record is read from the
  617. file.</p>
  618. </dd></dl>
  619. </section>
  620. <section id="writer-objects">
  621. <h2>Writer Objects<a class="headerlink" href="#writer-objects" title="Link to this heading">¶</a></h2>
  622. <p><a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects (<a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> instances and objects returned by
  623. the <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-func docutils literal notranslate"><span class="pre">writer()</span></code></a> function) have the following public methods. A <em>row</em> must be
  624. an iterable of strings or numbers for <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects and a dictionary
  625. mapping fieldnames to strings or numbers (by passing them through <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>
  626. first) for <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> objects. Note that complex numbers are written
  627. out surrounded by parens. This may cause some problems for other programs which
  628. read CSV files (assuming they support complex numbers at all).</p>
  629. <dl class="py method">
  630. <dt class="sig sig-object py" id="csv.csvwriter.writerow">
  631. <span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">writerow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">row</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvwriter.writerow" title="Link to this definition">¶</a></dt>
  632. <dd><p>Write the <em>row</em> parameter to the writer’s file object, formatted according
  633. to the current <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>. Return the return value of the call to the
  634. <em>write</em> method of the underlying file object.</p>
  635. <div class="versionchanged">
  636. <p><span class="versionmodified changed">Changed in version 3.5: </span>Added support of arbitrary iterables.</p>
  637. </div>
  638. </dd></dl>
  639. <dl class="py method">
  640. <dt class="sig sig-object py" id="csv.csvwriter.writerows">
  641. <span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">writerows</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">rows</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvwriter.writerows" title="Link to this definition">¶</a></dt>
  642. <dd><p>Write all elements in <em>rows</em> (an iterable of <em>row</em> objects as described
  643. above) to the writer’s file object, formatted according to the current
  644. dialect.</p>
  645. </dd></dl>
  646. <p>Writer objects have the following public attribute:</p>
  647. <dl class="py attribute">
  648. <dt class="sig sig-object py" id="csv.csvwriter.dialect">
  649. <span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">dialect</span></span><a class="headerlink" href="#csv.csvwriter.dialect" title="Link to this definition">¶</a></dt>
  650. <dd><p>A read-only description of the dialect in use by the writer.</p>
  651. </dd></dl>
  652. <p>DictWriter objects have the following public method:</p>
  653. <dl class="py method">
  654. <dt class="sig sig-object py" id="csv.DictWriter.writeheader">
  655. <span class="sig-prename descclassname"><span class="pre">DictWriter.</span></span><span class="sig-name descname"><span class="pre">writeheader</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictWriter.writeheader" title="Link to this definition">¶</a></dt>
  656. <dd><p>Write a row with the field names (as specified in the constructor) to
  657. the writer’s file object, formatted according to the current dialect. Return
  658. the return value of the <a class="reference internal" href="#csv.csvwriter.writerow" title="csv.csvwriter.writerow"><code class="xref py py-meth docutils literal notranslate"><span class="pre">csvwriter.writerow()</span></code></a> call used internally.</p>
  659. <div class="versionadded">
  660. <p><span class="versionmodified added">New in version 3.2.</span></p>
  661. </div>
  662. <div class="versionchanged">
  663. <p><span class="versionmodified changed">Changed in version 3.8: </span><a class="reference internal" href="#csv.DictWriter.writeheader" title="csv.DictWriter.writeheader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writeheader()</span></code></a> now also returns the value returned by
  664. the <a class="reference internal" href="#csv.csvwriter.writerow" title="csv.csvwriter.writerow"><code class="xref py py-meth docutils literal notranslate"><span class="pre">csvwriter.writerow()</span></code></a> method it uses internally.</p>
  665. </div>
  666. </dd></dl>
  667. </section>
  668. <section id="examples">
  669. <span id="csv-examples"></span><h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2>
  670. <p>The simplest example of reading a CSV file:</p>
  671. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  672. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;some.csv&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  673. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  674. <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  675. <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  676. </pre></div>
  677. </div>
  678. <p>Reading a file with an alternate format:</p>
  679. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  680. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;passwd&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  681. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39;:&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_NONE</span><span class="p">)</span>
  682. <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  683. <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  684. </pre></div>
  685. </div>
  686. <p>The corresponding simplest possible writing example is:</p>
  687. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  688. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;some.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  689. <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  690. <span class="n">writer</span><span class="o">.</span><span class="n">writerows</span><span class="p">(</span><span class="n">someiterable</span><span class="p">)</span>
  691. </pre></div>
  692. </div>
  693. <p>Since <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> is used to open a CSV file for reading, the file
  694. will by default be decoded into unicode using the system default
  695. encoding (see <a class="reference internal" href="locale.html#locale.getencoding" title="locale.getencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.getencoding()</span></code></a>). To decode a file
  696. using a different encoding, use the <code class="docutils literal notranslate"><span class="pre">encoding</span></code> argument of open:</p>
  697. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  698. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;some.csv&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  699. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  700. <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  701. <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  702. </pre></div>
  703. </div>
  704. <p>The same applies to writing in something other than the system default
  705. encoding: specify the encoding argument when opening the output file.</p>
  706. <p>Registering a new dialect:</p>
  707. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  708. <span class="n">csv</span><span class="o">.</span><span class="n">register_dialect</span><span class="p">(</span><span class="s1">&#39;unixpwd&#39;</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39;:&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_NONE</span><span class="p">)</span>
  709. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;passwd&#39;</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  710. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s1">&#39;unixpwd&#39;</span><span class="p">)</span>
  711. </pre></div>
  712. </div>
  713. <p>A slightly more advanced use of the reader — catching and reporting errors:</p>
  714. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span><span class="o">,</span> <span class="nn">sys</span>
  715. <span class="n">filename</span> <span class="o">=</span> <span class="s1">&#39;some.csv&#39;</span>
  716. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  717. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  718. <span class="k">try</span><span class="p">:</span>
  719. <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  720. <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  721. <span class="k">except</span> <span class="n">csv</span><span class="o">.</span><span class="n">Error</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  722. <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="s1">&#39;file </span><span class="si">{}</span><span class="s1">, line </span><span class="si">{}</span><span class="s1">: </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">reader</span><span class="o">.</span><span class="n">line_num</span><span class="p">,</span> <span class="n">e</span><span class="p">))</span>
  723. </pre></div>
  724. </div>
  725. <p>And while the module doesn’t directly support parsing strings, it can easily be
  726. done:</p>
  727. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  728. <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">([</span><span class="s1">&#39;one,two,three&#39;</span><span class="p">]):</span>
  729. <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
  730. </pre></div>
  731. </div>
  732. <p class="rubric">Footnotes</p>
  733. <aside class="footnote-list brackets">
  734. <aside class="footnote brackets" id="id4" role="doc-footnote">
  735. <span class="label"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></span>
  736. <span class="backrefs">(<a role="doc-backlink" href="#id1">1</a>,<a role="doc-backlink" href="#id2">2</a>)</span>
  737. <p>If <code class="docutils literal notranslate"><span class="pre">newline=''</span></code> is not specified, newlines embedded inside quoted fields
  738. will not be interpreted correctly, and on platforms that use <code class="docutils literal notranslate"><span class="pre">\r\n</span></code> linendings
  739. on write an extra <code class="docutils literal notranslate"><span class="pre">\r</span></code> will be added. It should always be safe to specify
  740. <code class="docutils literal notranslate"><span class="pre">newline=''</span></code>, since the csv module does its own
  741. (<a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal</span></a>) newline handling.</p>
  742. </aside>
  743. </aside>
  744. </section>
  745. </section>
  746. <div class="clearer"></div>
  747. </div>
  748. </div>
  749. </div>
  750. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  751. <div class="sphinxsidebarwrapper">
  752. <div>
  753. <h3><a href="../contents.html">Table of Contents</a></h3>
  754. <ul>
  755. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a><ul>
  756. <li><a class="reference internal" href="#module-contents">Module Contents</a></li>
  757. <li><a class="reference internal" href="#dialects-and-formatting-parameters">Dialects and Formatting Parameters</a></li>
  758. <li><a class="reference internal" href="#reader-objects">Reader Objects</a></li>
  759. <li><a class="reference internal" href="#writer-objects">Writer Objects</a></li>
  760. <li><a class="reference internal" href="#examples">Examples</a></li>
  761. </ul>
  762. </li>
  763. </ul>
  764. </div>
  765. <div>
  766. <h4>Previous topic</h4>
  767. <p class="topless"><a href="fileformats.html"
  768. title="previous chapter">File Formats</a></p>
  769. </div>
  770. <div>
  771. <h4>Next topic</h4>
  772. <p class="topless"><a href="configparser.html"
  773. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code> — Configuration file parser</a></p>
  774. </div>
  775. <div role="note" aria-label="source link">
  776. <h3>This Page</h3>
  777. <ul class="this-page-menu">
  778. <li><a href="../bugs.html">Report a Bug</a></li>
  779. <li>
  780. <a href="https://github.com/python/cpython/blob/main/Doc/library/csv.rst"
  781. rel="nofollow">Show Source
  782. </a>
  783. </li>
  784. </ul>
  785. </div>
  786. </div>
  787. <div id="sidebarbutton" title="Collapse sidebar">
  788. <span>«</span>
  789. </div>
  790. </div>
  791. <div class="clearer"></div>
  792. </div>
  793. <div class="related" role="navigation" aria-label="related navigation">
  794. <h3>Navigation</h3>
  795. <ul>
  796. <li class="right" style="margin-right: 10px">
  797. <a href="../genindex.html" title="General Index"
  798. >index</a></li>
  799. <li class="right" >
  800. <a href="../py-modindex.html" title="Python Module Index"
  801. >modules</a> |</li>
  802. <li class="right" >
  803. <a href="configparser.html" title="configparser — Configuration file parser"
  804. >next</a> |</li>
  805. <li class="right" >
  806. <a href="fileformats.html" title="File Formats"
  807. >previous</a> |</li>
  808. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  809. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  810. <li class="switchers">
  811. <div class="language_switcher_placeholder"></div>
  812. <div class="version_switcher_placeholder"></div>
  813. </li>
  814. <li>
  815. </li>
  816. <li id="cpython-language-and-version">
  817. <a href="../index.html">3.12.3 Documentation</a> &#187;
  818. </li>
  819. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  820. <li class="nav-item nav-item-2"><a href="fileformats.html" >File Formats</a> &#187;</li>
  821. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a></li>
  822. <li class="right">
  823. <div class="inline-search" role="search">
  824. <form class="inline-search" action="../search.html" method="get">
  825. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  826. <input type="submit" value="Go" />
  827. </form>
  828. </div>
  829. |
  830. </li>
  831. <li class="right">
  832. <label class="theme-selector-label">
  833. Theme
  834. <select class="theme-selector" oninput="activateTheme(this.value)">
  835. <option value="auto" selected>Auto</option>
  836. <option value="light">Light</option>
  837. <option value="dark">Dark</option>
  838. </select>
  839. </label> |</li>
  840. </ul>
  841. </div>
  842. <div class="footer">
  843. &copy;
  844. <a href="../copyright.html">
  845. Copyright
  846. </a>
  847. 2001-2024, Python Software Foundation.
  848. <br />
  849. This page is licensed under the Python Software Foundation License Version 2.
  850. <br />
  851. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  852. <br />
  853. See <a href="/license.html">History and License</a> for more information.<br />
  854. <br />
  855. The Python Software Foundation is a non-profit corporation.
  856. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  857. <br />
  858. <br />
  859. Last updated on Apr 09, 2024 (13:47 UTC).
  860. <a href="/bugs.html">Found a bug</a>?
  861. <br />
  862. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  863. </div>
  864. </body>
  865. </html>
上海开阖软件有限公司 沪ICP备12045867号-1