How to import a csv-file into a data array?

前端 未结 2 658
悲哀的现实
悲哀的现实 2021-01-01 18:40

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.t         


        
相关标签:
2条回答
  • 2021-01-01 19:02

    You can use pandas library or numpy to read the CSV file. If your file is tab-separated then use '\t' in place of comma in both sep and delimiter arguments below.

    import pandas as pd 
    myFile = pd.read_csv('filepath', sep=',')
    

    Or

     import numpy as np
     myFile = np.genfromtxt('filepath', delimiter=',')
    
    0 讨论(0)
  • 2021-01-01 19:22

    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.

    0 讨论(0)
提交回复
热议问题