Home > Mobile >  Export pandas dataframe to .txt file without a delimeter
Export pandas dataframe to .txt file without a delimeter

Time:08-22

I am trying to export my pandas dataframe to .txt file without a delimiter in .txt file.

Example dataframe:

enter image description here

I want to export this dataframe as fixed format text file.

  1. 4 chars always reserved for id. In our case 1 in the dataframe will look '1 ' in our txt file
  2. 16 chars always reserved for name

The output must look like this ID starts at 1st position and name must start at 5th position always

enter image description here

I am writing the below code but it still uses the delimeter

df.to_csv(r'path to txt file/test.txt',
          sep = " ",
          header=None,
          index = False,
          quoting=csv.QUOTE_NONE,
          escapechar=" ")

Can anyone suggest how to achieve this?

CodePudding user response:

Have you tried using the following configuration:

sep ='\t'

This should create a tab separated file.

Edited:

If what you want is a fixed width format then you should convert the dataframe to a numpy array and use the following solution: pandas-write-dataframe-in-fixed-width-formatted-lines-to-a-file

CodePudding user response:

I found the answer to my question. To convert a dataframe to fixed width formatted .txt file, one must use the np.savetxt() function.

np.savetxt(r'path to txt file/test.txt', df.values, fmt='%-4s%-12s',encoding='UTF-8')

The above piece of code helps you convert to .txt file without a delimiter between two columns.

I get 4 chars always assigned to ID. '-' indicates that it is left justified. Similarly, 12 chars always assigned to Name column starting from 5th position

  • Related