parse a csv file into a text file

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Feb 6 09:49:59 CET 2014


Zhen Zhang writes:
...
> I am currently running python 2.7.
> 
> Yes, i thought there must be a print function in python like fprint
> in C++ that allows you to print into a file directly.
>
> But i google about "print string into text file" I got answers using
> f.write() instead. :)

Indeed. The first Python hit for me with that query was the tutorial
page on I/O in Python 2, and it does exactly that.
<http://docs.python.org/2/tutorial/inputoutput.html>

That page does refer to the spec of the print statement, where you can
find the way to redirect the output to a file, but you need to be able
to read formal syntax specifications like this:

print_stmt ::=  "print" ([expression ("," expression)* [","]]
                | ">>" expression [("," expression)+ [","]])

The relevant pattern is the second alternative, after the vertical
bar, which can be instantiated this way:

  print >> f, e0, e1

There is one object f with a .write method, and one or more
expressions whose values get written using f.write; the effect of an
optional comma at end is also specified there. Not tutorial-level.
<http://docs.python.org/2/reference/simple_stmts.html#print>

But I use the newer print function even if I have to use 2.7,
something like this:

  from __future__ import print_function
  f = open("test.txt", "w")
  print("hello?", "see me?", file=f)
  f.close()

It does a modest amount of formatting: the value of the keyword
argument sep is written between the values, and the value of end is
written at end.



More information about the Python-list mailing list