简体   繁体   English

在python中导入csv文件

[英]importing csv file in python

I want to import CSV files in a python script. 我想在python脚本中导入CSV文件。 Column and row numbers are not fixed , first row contains name of the variables and next rows are values of those variables. 列号和行号不是固定的,第一行包含变量的名称,下一行是这些变量的值。 I am new to Python, any help is appreciated. 我是Python新手,不胜感激。 thanks. 谢谢。

import csv
csv_reader = csv.reader(open(path_file + filename, 'rb'))
fields = []
data = []
for i, row in enumerate(csv_reader):
    if i < 1:
        item = str(row[0]).split(';')
        for elem in item:
            fields.append(elem)
    else:
        obj_val = {}
        items = str(row[0]).decode(codes).split(';')
        for i, item in enumerate(items):
            obj_val[fields[i]] = item
        data.append(obj_val)
  • fields - field 领域-领域
  • data - rows from csv 数据-CSV中的行

So as not to just give out a homework answer, but to still point you in the right direction; 为了不只是给出家庭作业的答案,而还要指出正确的方向; import the CSV module. 导入CSV模块。 If you're using Python 3.5 here's the link to the doc. 如果您使用的是Python 3.5,则这是文档的链接 If you want to see the doc for a different version, use the drop-down on the top-left of the page to select it. 如果要查看其他版本的文档,请使用页面左上角的下拉列表将其选中。

Anyway... 无论如何...

You'll want to open the CSV file like you would any other, then use the CSV module to read the content. 您将要像打开其他任何文件一样打开CSV文件,然后使用CSV模块读取内容。 Iterating over each row in the file will return you a list of strings; 遍历文件中的每一行将返回一个字符串列表。 which are the contents of that row. 该行的内容。

For example: 例如:

['Header 1', 'Header 2', 'Header 3'...]
['A1', 'A2', 'A3'...]
['B1', 'B2', 'B3'...]
['C1', 'C2', 'C3'...]
...

First of all, at the top of the code do import csv 首先,在代码的顶部import csv

After that you need to set a variable name; 之后,您需要设置一个变量名。 this is so you can open the CSV file. 这样您就可以打开CSV文件。 For example, data=open('CSV name', 'rt') You will need to fill in where it says CSV name. 例如, data=open('CSV name', 'rt')您需要填写显示CSV名称的位置。 That's how you open it. 那就是你打开它的方式。

To read a CSV file, you set another variable. 要读取CSV文件,请设置另一个变量。 For example, data2=csv.reader(data) 例如, data2=csv.reader(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM