Mahmoud Al-Haroon
Mahmoud Al-Haroon

Reputation: 2449

How to convert txt to excel file

I have a txt file looks like this:

Cellname;Ncellname;Technology
52822;13621;GSM;
52822;13622;GSM;
52822;13623;GSM;
52822;16322;UMTS;
52822;16323;UMTS;
52822;16324;UMTS;
52822;16361;UMTS;
52822;16362;UMTS;
52822;16363;UMTS;

I tried to convert it using the below code:

import pandas as pd
import os



excel = 'gsmrelation_mnm.txt'
df = pd.read_csv(os.path.join(os.path.dirname(__file__), excel))
df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1')

but I found this error:

Traceback (most recent call last):
  File "C:/Users/haroo501/PycharmProjects/MyLiveRobo/convert_txt_csv.py", line 8, in <module>
    df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1')
  File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\core\generic.py", line 2250, in to_excel
    formatter.write(
  File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\io\formats\excel.py", line 730, in write
    writer = ExcelWriter(_stringify_path(writer), engine=engine)
  File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\io\excel\_openpyxl.py", line 19, in __init__
    from openpyxl.workbook import Workbook
ModuleNotFoundError: No module named 'openpyxl'

enter image description here

How to solve this problem

Upvotes: 1

Views: 896

Answers (3)

Louis Hulot
Louis Hulot

Reputation: 395


import pandas as pd 
file = pd.read_csv('input.txt', sep=';', index=False)
file.to_excel('output.xlsx', 'Sheet1')

Upvotes: 1

Kartheek
Kartheek

Reputation: 164

I tried following,

finally what you expected

import pandas as pd

df = pd.read_csv('gsmrelation_mnm.txt', sep = ';', header=None, names=['Cellname', 'Ncellname', 'Technology'])
df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1', index=False, header=None)

Upvotes: 0

Jatin Chauhan
Jatin Chauhan

Reputation: 325

Try this:

import pandas as pd

excel = 'test.txt'

df = pd.read_csv(excel,sep=';')

column_indexes = list(df.columns)

df.reset_index(inplace=True)
df.drop(columns=df.columns[-1], inplace=True)

column_indexes = dict(zip(list(df.columns),column_indexes))

df.rename(columns=column_indexes, inplace=True)

df

and then

df.to_excel('output.xlsx', 'Sheet1')

and in case you don't want the indexes in the output sheet, use this

df.to_excel('output.xlsx', 'Sheet1', index=False)

Upvotes: 1

Related Questions