简体   繁体   中英

How to delete quotes from data read from .csv file?

I am trying to read several .csv files from a directory with the following code and then store each line of output result as a row of a matrix:

import os, fnmatch
import csv
listOfFiles = os.listdir('C:/Users/m/Desktop/csv_files')  
pattern = "*.csv"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        with open(entry, newline='') as csvfile:
            spamreader = csv.reader(csvfile)
            for line in spamreader:
                print(line)

The output of the above code is like this:

['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'PRICE', 'YCLOSE', 'VOL', 'TICKS']
['13950309', '1000000.00', '1000000', '1000000', '1000000.00', '1000000.00', '1000000', '2100000', '74']
['13950326', '1050000.00', '1050010', '1050000', '1050001.00', '1050000.00', '1000000', '1648', '5']
['13950329', '1030200.00', '1060000', '1030200', '1044474.00', '1042265.00', '1050001', '28469', '108']

But I like to delete quotes from data and have rows like this:

[13971116, 1020002.00, 1020002, 1020000, 1020001.00, 1020000.00, 1020002, 107, 4]

And store them as rows of a matrix. How can I do that?(I have numpy library for matrix working).

Can you try the following:

import os, fnmatch
import csv
listOfFiles = os.listdir('C:/Users/m/Desktop/csv_files')  
pattern = "*.csv"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        with open(entry, newline='') as csvfile:
            spamreader = csv.reader(csvfile)
            for line in spamreader:
                try:
                    print(list(map(float, line)))
                except:
                    print(line)

In your code, line is already a list of strings-- no quotes. To get a matrix of rows of numbers, write:

with open(entry, newline='') as csvfile:
    spamreader = csv.reader(csvfile)
    data_matrix = list([ float(n) for n in row ] for row in spamreader)

and you're done.

Your values doesn't contain quotes. Quotes here are just string delimiters which indicate that values are strings.

If you need numbers you need to cast values to the desired type, for example if all your values are integers you can cast values using int(value)

Your code will be:

import os, fnmatch
import csv
listOfFiles = os.listdir('C:/Users/m/Desktop/csv_files')  
pattern = "*.csv"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        with open(entry, newline='') as csvfile:
            spamreader = csv.reader(csvfile)
            for line in spamreader:
                print(line)
                # create a new list casting all line values to integers
                line_ints = [int(val) for val in line]
                print(line_ints)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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