A
A
Asya2019-11-12 18:41:12
Python
Asya, 2019-11-12 18:41:12

How to convert txt to csv with given delimiter?

I have a text file input.txt, which contains the following lines:

1    @    2      @    3             @    4        @    5       @    6
x    @    123    @    one, two      @     56      @    abc     @
y    @    234    @    two; three    @             @    abc     @
z    @    456    @    three: one    @             @            @

how to convert it to dataframe in python to look like this?
1    2        3         4     5      6
x    123    one, two    56    abc   NA
y    234    two; three   NA   abc   NA
z    456    three: one   NA   NA    NA

and in output.csv it looked like this:
x,123,one, two,56,abc
y,234,two; three,,abc
z,456,three: one,,
tried
import pandas as pd

df = pd.read_csv('input.txt')
df.to_csv('output.csv', sep='@')

but it doesn't help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_, 2019-11-12
@asyaevloeva

When loading from a file, you can specify a delimiter

import pandas as pd

df = pd.read_csv('input.txt', sep='@')

Get a dataframe with your data from a txt file and then save as usual
df.to_csv('output.csv')

J
Juhani Lahtinen, 2019-11-12
@nukler

What does replace say about this?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question