从python读取csv文件 [英] Read csv file from python
问题描述
我在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)
文件中的文件:
file_full_name = os.path.join(INPUT_DIR,file)
print file_full_name
f = open(file_full_name,'r')
for f.readlines():
printLine:,line
def create_sql_file():
printHi
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系统优先级Data_01232013 - Copy.csv
行:PK **
问题?
首先,确保将文件从Excel转换为csv,使用
菜单。只是更改扩展名不起作用。您看到的输出是来自Excel原生格式的数据。
一旦您转换了文件,请使用 csv
模块:
<$对于os.listdir(INPUT_DIR)中的文件名,c $ c> import csv
$ b:
with open(os.path.join(INPUT_DIR,filename),dialect ='excel-tab') as infile:
reader = csv.reader(infile)
对于读取器中的行:
打印行
如果要读取原始Excel文件,请使用 xlrd
模块。以下是显示如何阅读Excel文件的示例。 p>
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?
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.
这篇关于从python读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!