Convert .CSV files to .DTA files in Python

后端 未结 2 1956
孤街浪徒
孤街浪徒 2021-01-24 11:11

I\'m looking to automate the process of converting many .CSV files into .DTA files via Python. .DTA files is the filetype that is handled by the Stata Statistics language.

2条回答
  •  醉梦人生
    2021-01-24 11:38

    You need rpy2 for Python and also the foreign package installed in R. You do that by starting R and typing install.packages("foreign"). You can then quit R and go back to Python.

    Then this:

    import rpy2.robjects as robjects
    robjects.r("require(foreign)")
    robjects.r('x=read.csv("test.csv")')
    robjects.r('write.dta(x,"test.dta")')
    

    You can construct the string passed to robjects.r from Python variables if you want, something like:

    robjects.r('x=read.csv("%s")' % fileName)
    

提交回复
热议问题