Splashlin
Splashlin

Reputation: 7585

Converting .txt file to .xls in Python

I have a file that is really in csv format but is being handed to me as a .txt. I need to take this file and transfer it to .xls format so I can upload it into Google Docs. Currently I have the code below but it is spitting out the file with everything on the line into the first cell instead of breaking out different cells for every comma value. Does anyone know how to solve this?

Thanks!

import os

fin = open(r"C:\Users\JohnDoe\Downloads\Report.txt", "r")
data_list = fin.readlines()
fin.close() # closes file

fout = open(r"C:\Users\JohnDoe\Desktop\Report.xls", "w")
fout.writelines(data_list)
fout.flush()
fout.close()

Upvotes: 1

Views: 6873

Answers (3)

Alvin K.
Alvin K.

Reputation: 4379

Try http://packages.python.org/openpyxl/ or for older excel files, check out this help page using pyExcelerator.

Upvotes: 0

agf
agf

Reputation: 176780

Just renaming it to .xls doesn't convert it to an Excel spreadsheet. But regardless, why would you convert it to .xls just to upload it to Google Docs?

If it's a .csv, just rename the file to .csv and upload it and it'll properly be detected as a spreadsheet.

Use os.rename:

import os

os.rename("C:\Users\JohnDoe\Downloads\Report.txt", 
          "C:\Users\JohnDoe\Downloads\Report.cvs")

if you really need to do it with Python.

If you need to get actual rows from the file instead of lines:

from csv import reader

for row in reader(open(r"C:\Users\JohnDoe\Downloads\Report.txt", 'rb')):
    # do something with row

will give you a list of cells for each line.

If you actually do need to work with an Excel spreadsheet, see http://www.python-excel.org/ and the xlwt package.

Upvotes: 6

teambob
teambob

Reputation: 2084

Your code is simply copying Report.txt into Report.xls

When opening Report.xls Excel is recognising it as a csv file, however it is not recognising the commas as delimiters.

You will need to use some kind of library to write proper Excel files. Look at Word's COM interface for example.

Upvotes: 0

Related Questions