PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to import a csv-file into a data array?

 August 28, 2022     csv, python, python-2.x     No comments   

Issue

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)

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:
    ???

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

Solution

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)

You can specify other delimiters, such as tab characters, by specifying them when creating the csv.reader:

    data = list(csv.reader(csvfile, delimiter='\t'))

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



Answered By - martineau
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing