1. <tfoot id='nLUzY'></tfoot>
        <bdo id='nLUzY'></bdo><ul id='nLUzY'></ul>

      <i id='nLUzY'><tr id='nLUzY'><dt id='nLUzY'><q id='nLUzY'><span id='nLUzY'><b id='nLUzY'><form id='nLUzY'><ins id='nLUzY'></ins><ul id='nLUzY'></ul><sub id='nLUzY'></sub></form><legend id='nLUzY'></legend><bdo id='nLUzY'><pre id='nLUzY'><center id='nLUzY'></center></pre></bdo></b><th id='nLUzY'></th></span></q></dt></tr></i><div id='nLUzY'><tfoot id='nLUzY'></tfoot><dl id='nLUzY'><fieldset id='nLUzY'></fieldset></dl></div>

      <legend id='nLUzY'><style id='nLUzY'><dir id='nLUzY'><q id='nLUzY'></q></dir></style></legend>

      <small id='nLUzY'></small><noframes id='nLUzY'>

      如何使用 Python 读写 CSV 文件?

      How do I read and write CSV files with Python?(如何使用 Python 读写 CSV 文件?)
      <i id='QlWk3'><tr id='QlWk3'><dt id='QlWk3'><q id='QlWk3'><span id='QlWk3'><b id='QlWk3'><form id='QlWk3'><ins id='QlWk3'></ins><ul id='QlWk3'></ul><sub id='QlWk3'></sub></form><legend id='QlWk3'></legend><bdo id='QlWk3'><pre id='QlWk3'><center id='QlWk3'></center></pre></bdo></b><th id='QlWk3'></th></span></q></dt></tr></i><div id='QlWk3'><tfoot id='QlWk3'></tfoot><dl id='QlWk3'><fieldset id='QlWk3'></fieldset></dl></div>
        <bdo id='QlWk3'></bdo><ul id='QlWk3'></ul>
          <tbody id='QlWk3'></tbody>

          <tfoot id='QlWk3'></tfoot>
          • <legend id='QlWk3'><style id='QlWk3'><dir id='QlWk3'><q id='QlWk3'></q></dir></style></legend>

              <small id='QlWk3'></small><noframes id='QlWk3'>

                本文介绍了如何使用 Python 读写 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                我有一个包含内容的文件 example.csv

                I have a file example.csv with the contents

                1,"A towel,",1.0
                42," it says, ",2.0
                1337,is about the most ,-1
                0,massively useful thing ,123
                -2,an interstellar hitchhiker can have.,3
                

                如何使用 Python 读取此 example.csv?

                How do I read this example.csv with Python?

                同样,如果我有

                data = [(1, "A towel,", 1.0),
                        (42, " it says, ", 2.0),
                        (1337, "is about the most ", -1),
                        (0, "massively useful thing ", 123),
                        (-2, "an interstellar hitchhiker can have.", 3)]
                

                如何使用 Python 将 data 写入 CSV 文件?

                How do I write data to a CSV file with Python?

                推荐答案

                这里有一些最小的完整示例如何读取 CSV 文件以及如何使用 Python 编写 CSV 文件.

                Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.

                纯 Python

                import csv
                
                # Define data
                data = [
                    (1, "A towel,", 1.0),
                    (42, " it says, ", 2.0),
                    (1337, "is about the most ", -1),
                    (0, "massively useful thing ", 123),
                    (-2, "an interstellar hitchhiker can have.", 3),
                ]
                
                # Write CSV file
                with open("test.csv", "wt") as fp:
                    writer = csv.writer(fp, delimiter=",")
                    # writer.writerow(["your", "header", "foo"])  # write header
                    writer.writerows(data)
                
                # Read CSV file
                with open("test.csv") as fp:
                    reader = csv.reader(fp, delimiter=",", quotechar='"')
                    # next(reader, None)  # skip the headers
                    data_read = [row for row in reader]
                
                print(data_read)
                

                之后,data_read的内容为

                [['1', 'A towel,', '1.0'],
                 ['42', ' it says, ', '2.0'],
                 ['1337', 'is about the most ', '-1'],
                 ['0', 'massively useful thing ', '123'],
                 ['-2', 'an interstellar hitchhiker can have.', '3']]
                

                请注意,CSV 仅读取字符串.您需要手动转换为列类型.

                Please note that CSV reads only strings. You need to convert to the column types manually.

                之前有一个 Python 2+3 版本(链接),但是放弃对 Python 2 的支持.删除 Python 2 的东西大大简化了这个答案.

                A Python 2+3 version was here before (link), but Python 2 support is dropped. Removing the Python 2 stuff massively simplified this answer.

                • 如何将数据作为字符串(而非文件)写入 csv 格式?
                • 如何将 io.StringIO() 与 csv 模块一起使用?:如果您想提供服务,这很有趣使用 Flask 即时生成 CSV,而无需将 CSV 实际存储在服务器上.
                • How do I write data into csv format as string (not file)?
                • How can I use io.StringIO() with the csv module?: This is interesting if you want to serve a CSV on-the-fly with Flask, without actually storing the CSV on the server.

                查看我的实用程序包 mpu 以获得超级简单和容易记住的一个:

                Have a look at my utility package mpu for a super simple and easy to remember one:

                import mpu.io
                data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
                mpu.io.write('example.csv', data)
                

                熊猫

                import pandas as pd
                
                # Read the CSV into a pandas data frame (df)
                #   With a df you can do many things
                #   most important: visualize data with Seaborn
                df = pd.read_csv('myfile.csv', sep=',')
                print(df)
                
                # Or export it in many ways, e.g. a list of tuples
                tuples = [tuple(x) for x in df.values]
                
                # or export it as a list of dicts
                dicts = df.to_dict().values()
                

                参见 read_csv 文档 了解更多信息.请注意,pandas 会自动推断是否有标题行,但您也可以手动设置.

                See read_csv docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.

                如果您还没有听说过 Seaborn,我建议您看看它.

                If you haven't heard of Seaborn, I recommend having a look at it.

                许多其他库都支持读取 CSV 文件,例如:

                Reading CSV files is supported by a bunch of other libraries, for example:

                • dask.dataframe.read_csv
                • spark.read.csv
                1,"A towel,",1.0
                42," it says, ",2.0
                1337,is about the most ,-1
                0,massively useful thing ,123
                -2,an interstellar hitchhiker can have.,3
                

                常见的文件结尾

                .csv

                在将 CSV 文件读取到元组/字典列表或 Pandas 数据框后,它只是在处理此类数据.没有特定的 CSV.

                After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.

                • JSON:非常适合编写人类可读的数据;非常常用(读写)
                • CSV:超级简单的格式(读写)
                • YAML:易于阅读,类似于 JSON(读写)
                • pickle:一种 Python 序列化格式(读写)
                • MessagePack (Python 包):更紧凑的表示(读写)
                • HDF5 (Python 包):非常适合矩阵(读写)
                • XML:也存在 *sigh* (阅读 & 写)
                • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
                • CSV: Super simple format (read & write)
                • YAML: Nice to read, similar to JSON (read & write)
                • pickle: A Python serialization format (read & write)
                • MessagePack (Python package): More compact representation (read & write)
                • HDF5 (Python package): Nice for matrices (read & write)
                • XML: exists too *sigh* (read & write)

                对于您的应用程序,以下内容可能很重要:

                For your application, the following might be important:

                • 其他编程语言的支持
                • 读/写性能
                • 紧凑性(文件大小)

                另请参阅:数据序列化格式的比较

                如果您正在寻找一种制作配置文件的方法,您可能想阅读我的短文 Python 中的配置文件

                In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

                这篇关于如何使用 Python 读写 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                Split a Pandas column of lists into multiple columns(将 Pandas 的列表列拆分为多列)
                How does the @property decorator work in Python?(@property 装饰器在 Python 中是如何工作的?)
                What is the difference between old style and new style classes in Python?(Python中的旧样式类和新样式类有什么区别?)
                How to break out of multiple loops?(如何打破多个循环?)
                How to put the legend out of the plot(如何将传说从情节中剔除)
                Why is the output of my function printing out quot;Nonequot;?(为什么我的函数输出打印出“无?)
                  <bdo id='ZFkYJ'></bdo><ul id='ZFkYJ'></ul>
                  <i id='ZFkYJ'><tr id='ZFkYJ'><dt id='ZFkYJ'><q id='ZFkYJ'><span id='ZFkYJ'><b id='ZFkYJ'><form id='ZFkYJ'><ins id='ZFkYJ'></ins><ul id='ZFkYJ'></ul><sub id='ZFkYJ'></sub></form><legend id='ZFkYJ'></legend><bdo id='ZFkYJ'><pre id='ZFkYJ'><center id='ZFkYJ'></center></pre></bdo></b><th id='ZFkYJ'></th></span></q></dt></tr></i><div id='ZFkYJ'><tfoot id='ZFkYJ'></tfoot><dl id='ZFkYJ'><fieldset id='ZFkYJ'></fieldset></dl></div>

                      <tbody id='ZFkYJ'></tbody>
                    <legend id='ZFkYJ'><style id='ZFkYJ'><dir id='ZFkYJ'><q id='ZFkYJ'></q></dir></style></legend>
                    <tfoot id='ZFkYJ'></tfoot>

                    • <small id='ZFkYJ'></small><noframes id='ZFkYJ'>