Read csv file from python [duplicate]

落爺英雄遲暮 提交于 2019-11-30 16:35:53

问题


I had some data in excel file. I changed the file to .csv file and tried to write some python code to read the file.

But I am getting some unpredictable outputs. My Code is like this:

INPUT_DIR = os.path.join(os.getcwd(),"Input")
OUTPUT_DIR = os.path.join(os.getcwd(),"Output")
print INPUT_DIR, OUTPUT_DIR 

def read_csv():    
    files = os.listdir(INPUT_DIR)
    for file in files:
        file_full_name = os.path.join(INPUT_DIR,file)
        print file_full_name
        f = open(file_full_name,'r')
        for line in f.readlines():
            print "Line: ", line

def create_sql_file():
    print "Hi"


if __name__ == '__main__':
    read_csv()
    create_sql_file()

This gives very peculiar output:

 C:\calcWorkspace\13.1.1.0\PythonTest\src\Input C:\calcWorkspace\13.1.1.0\PythonTest\src\Output
C:\calcWorkspace\13.1.1.0\PythonTest\src\Input\Country Risk System Priority Data_01232013 - Copy.csv
Line:  PK**

Does someone know of this issue?


回答1:


First, make sure you converted the file from Excel to csv, using the Save As menu from Excel. Simply changing the extension doesn't work. The output you are seeing is data from Excel's native format.

Once you have converted the files, use the csv module:

import csv

for filename in os.listdir(INPUT_DIR):
   with open(os.path.join(INPUT_DIR,filename), dialect='excel-tab') as infile:
      reader = csv.reader(infile)
      for row in reader:
          print row

If you want to read raw Excel files, use the xlrd module. Here is a sample that shows how to read Excel files.



来源:https://stackoverflow.com/questions/14725020/read-csv-file-from-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!