[Tutor] print to file probelm
Peter Otten
__peter__ at web.de
Mon Aug 15 22:02:36 CEST 2011
John Collins wrote:
> Hi,
> I'm a baffled beginner. The script below is one of a suite of scripts
> written by Simon Tatham a decade ago;
> http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/
> http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/polyhedra.tar.gz
>
> OS: WinXP
> Py Ver: 2.7
> Script: canvas.py
>
> It reads from a file name in the command line and should print to a file
> name also specified in the command line. It inputs and runs fine but
> outputs to the command prompt *screen* while creating and *empty* output
> file of the name specified? I cannot figure out why?
> args = sys.argv[1:]
>
> if len(args) > 0:
> infile = open(args[0], "r")
> args = args[1:]
> else:
> infile = sys.stdin
>
> if len(args) > 0:
> outfile = open(args[0], "w")
> args = args[1:]
> else:
> outfile = sys.stdout
If you pass two args this will open two files, infile for reading, and
outfile for writing. While infile is actually used...
> while 1:
> s = infile.readline()
> if s == "": break
...
> infile.close()
... outfile is not. The print statement
> print s
will always write to stdout. You can modify the print statement to
print >> outfile, s
or use
outfile.write(s + "\n")
instead. It is good style to close the file explicitly when you're done with
outfile.close()
More information about the Tutor
mailing list