从Python读取csv文件
我有一些数据在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**
有没有人知道这是怎么回事?
1 个回答
11
首先,确保你把文件从Excel格式转换成csv格式,方法是使用Excel里的另存为
菜单。仅仅改变文件的后缀名是没用的。你看到的输出其实是Excel原生格式的数据。
一旦你转换好了文件,就可以使用csv
模块来处理它们:
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