我在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**
有人知道这个问题吗?
答案 0 :(得分:11)
首先,确保使用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。这是一个显示如何阅读Excel文件的sample。