Skip to content
Advertisement

python: Convert a textfile into csv file

Say I want to convert a textfile (in.txt) into a csv file (out.csv) using Python.

in.txt:

JavaScript

The output file out.csv should looks like this:

JavaScript

So far I have done this:

JavaScript

How can I do this?

Advertisement

Answer

A solution that would allow either a single or multiple records:

JavaScript

Some explanation:

  • everything sits in a function, so you can use it repeatedly and for different files and record sizes
  • the while True loop loops forever, until a break statement breaks out of it
  • the try .. except StopIteration catches when next(in_f) tries to read beyond the end of the file
  • rec is created as a dictionary, which is handy in case you need to further manipulate the values or want to use the record elsewhere, although it’s not strictly speaking the most efficient way to perform the task.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement