如何将csv文件导入数据数组? [英] How to import a csv-file into a data array?

查看:251
本文介绍了如何将csv文件导入数据数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在脚本中有一行代码,该脚本从文本文件中导入数据,值之间有很多空格,以供以后使用.

I have a line of code in a script that imports data from a text file with lots of spaces between values into an array for use later.

textfile = open('file.txt')
data = []
for line in textfile:
    row_data = line.strip("\n").split()
    for i, item in enumerate(row_data):
        try:
            row_data[i] = float(item)
        except ValueError:
            pass
    data.append(row_data)

我需要将其从文本文件更改为csv文件.我不想只是将此文本更改为以逗号分隔(因为某些值如果用引号引起来,则可以使用逗号).幸运的是,我看到有一个可以导入的csv库可以处理此问题.

I need to change this from a text file to a csv file. I don't want to just change this text to split on commas (since some values can have commas if they're in quotes). Luckily I saw there is a csv library I can import that can handle this.

import csv
with open('file.csv', 'rb') as csvfile:
    ???

如何将csv文件加载到数据数组中?

How can I load the csv file into the data array?

如果有所作为,这将是数据的使用方式:

If it makes a difference, this is how the data will be used:

row = 0
for row_data in (data):
    worksheet.write_row(row, 0, row_data)
    row += 1

推荐答案

假设csv文件用逗号分隔,在Python 3中使用csv模块的最简单方法可能是:

Assuming the csv file is delimited with commas, the simplest way using the csv module in Python 3 would probably be:

import csv

with open('testfile.csv', newline='') as csvfile:
    data = list(csv.reader(csvfile))

print(data)

对于Python 2,使用open('testfile.csv', 'rb')打开文件.

For Python 2, use open('testfile.csv', 'rb') to open the file.

这篇关于如何将csv文件导入数据数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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