如何在不使用外部库(例如Numpy,Pandas)的情况下读取CSV文件? [英] How to read a CSV file without using external libraries (such as Numpy, Pandas)?

查看:70
本文介绍了如何在不使用外部库(例如Numpy,Pandas)的情况下读取CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个通常出现在访谈中的问题.

This is a question that usually appears in interviews.

我知道如何使用 Pandas 读取csv文件.

I know how to read csv files using Pandas.

但是,我一直在努力寻找一种无需使用外部库即可读取文件的方法.

However I am struggling to find a way to read files without using external libraries.

Python是否附带任何有助于读取csv文件的模块?

Does Python come with any module that would help read csv files?

推荐答案

您很可能将需要一个库来读取CSV文件.尽管您可能自己打开和解析数据,但这将是乏味且耗时的.幸运的是,python随附了一个标准的 csv 模块,您无需进行pip安装!您可以这样读取文件:

You most likely will need a library to read a CSV file. While you could potentially open and parse the data yourself, this would be tedious and time consuming. Luckily python comes with a standard csv module that you won't have to pip install! You can read your file in like this:

import csv

with open('file.csv', 'r') as file:
    my_reader = csv.reader(file, delimiter=',')
    for row in my_reader:
        print(row)

这将向您显示每个 row 作为列表被读取.然后,您可以根据索引对其进行处理!如 https://docs.python.org所述,还有其他读取数据的方法./3/library/csv.html 其中之一将创建字典而不是列表!

This will show you that each row is being read in as a list. You can then process it based on index! There are other ways to read in data too as described at https://docs.python.org/3/library/csv.html one of which will create a dictionary instead of a list!

您将您的github链接到了我剪断的项目

You linked your github for the project I took the snip

product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3

将其另存为 file.csv 并使用我发布的上述代码运行它.结果:

Saved it as file.csv and ran it with the above code I posted. Result:

['product_id', 'product_name', 'aisle_id', 'department_id']
['9327', 'Garlic Powder', '104', '13']
['17461', 'Air Chilled Organic Boneless Skinless Chicken Breasts', '35', '12']
['17668', 'Unsweetened Chocolate Almond Breeze Almond Milk', '91', '16']
['28985', 'Michigan Organic Kale', '83', '4']
['32665', 'Organic Ezekiel 49 Bread Cinnamon Raisin', '112', '3']
['33120', 'Organic Egg Whites', '86', '16']
['45918', 'Coconut Butter', '19', '13']
['46667', 'Organic Ginger Root', '83', '4']
['46842', 'Plain Pre-Sliced Bagels', '93', '3']

这就是您在问题中所问的内容.我不会为您做您的项目,您应该可以在这里工作.

This does what you have asked in your question. I am not going to do your project for you, you should be able to work it from here.

这篇关于如何在不使用外部库(例如Numpy,Pandas)的情况下读取CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆