Skip to content
Advertisement

Converting a 3 column text file to csv in python?

I have a text file in in .txt format and I need it in .CSV format. It has 3 columns: timestamp, weight, voltage.

Does anyone know a way to convert a .txt to .csv?

The data I have is in this format:

time_stamp      value     voltage 
1606148833000 1669.00    0.146
1606148641970 7256.000   0.907     
1606148642212 7090.000   0.886     
1606148642461 6880.000   0.860     
1606148642713 6727.000   0.841     
1606148642963 6646.000   0.831     

I can’t seem to format the above, there are 3 spaces (or a single tab) in-between values.

I’ve tried pandas, the built-in CSV module, bash shell, and none are working for me.

Advertisement

Answer

I think this should work

import pandas as pd
df = pd.read_csv('file.txt',delim_whitespace = True)
df.to_csv('file.csv',index=None)

the key argument being delim_whitespace = True, judging by the sample data you posted

If this does not work please paste the error you get and all, or a bigger chunk, of your file

here replace ‘file.txt’ with the path to your txt file and ‘file.csv’ the name of the file you want this saved in

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement