2015-05-28 1901 views
1

我在使用python中的panda将多个.dv文件同时转换为.csv时遇到问题,能否帮助我解决这个问题,因为我在四个文件夹中有不同的文件,都包含.dta文件?从.dta(stata)将文件转换为.csv

+3

请出示你的努力,但目前还不清楚你在哪里停留在 – EdChum

回答

2

pandas.io模块有一个read_stata功能:http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.stata.read_stata.html

这会将单个stata文件读入数据框。从那里您可以使用数据框的.to_csv方法以您需要的格式保存新文件。

当涉及到让所有在目录中的数据,我想你最快的前进路径看起来像这样(未经):

import glob 
import os 
import pandas 

my_directories = ['/path/to/first', '/path/to/second', ..., '/path/to/nth'] 
for my_dir in my_directories: 
    stata_files = glob.glob(os.path.join(my_dir, '*.dta')) # collects all the stata files 
    for file in stata_files: 
     # get the file path/name without the ".dta" extension 
     file_name, file_extension = os.path.splitext(file) 

     # read your data 
     df = pandas.read_stata(file, ...) 

     # save the data and never think about stata again :) 
     df.to_csv(file_name + '.csv') 
+0

谢谢。它非常好用:-) –