【问题标题】:Read csv file from python [duplicate]从python读取csv文件[重复]
【发布时间】:2013-01-21 09:53:30
【问题描述】:

我在 excel 文件中有一些数据。我将文件更改为 .csv 文件并尝试编写一些 python 代码来读取文件。

但我得到了一些不可预测的输出。我的代码是这样的:

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()

这给出了非常奇特的输出:

 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**

有人知道这个问题吗?

【问题讨论】:

  • 您是否尝试在简单的文本编辑器中打开文件以验证其内容?

标签: python csv xls


【解决方案1】:

首先,确保使用 Excel 中的 Save As 菜单将文件从 Excel 转换为 csv。简单地更改扩展名是行不通的。您看到的输出是 Excel 原生格式的数据。

转换文件后,使用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

如果您想读取原始 Excel 文件,请使用xlrd module。这是一个sample,它展示了如何读取 Excel 文件。

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2016-10-07
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多