Search code examples
pythonpandasxlsx

How to create .dat file with multiple spaces as delimiter from .xlsx file


I have an xlsx file, where each row corresponds to a sample with associated features in each column, as shown here: xlsx file example

I am trying to convert this xlsx file into a dat file, with multiple spaces separating the columns, as displayed in the example below:

samples      property  feature1  feature2  feature3
sample1       3.0862    0.8626    0.7043    0.6312
sample2       2.8854    0.7260    0.7818    0.6119
sample3       0.6907    0.4943    0.0044    0.4420
sample4       0.9902    0.0106    0.0399    0.9877
sample5       0.7242    0.0970    0.3199    0.5504

I have tried doing this by creating a dataframe in pandas and using dataframe.to_csv to save the file as a .dat, but it only allows me to use one character as a delimiter. Does anyone know how I might go about creating a file like the one above?


Solution

  • You can use the string representation to_string of the dataframe, imported by pandas from Excel:

    df = pd.read_excel('input.xlsx')
    with open ('output.dat', 'w') as f:
        f.write(df.to_string(index=False))