If you're new to Python
and VPython: Introduction

A VPython tutorial

Pictures of 3D objects

What's new in VPython 6

VPython web site
VPython license
Python web site
Math module (sqrt etc.)
Numpy module (arrays)

Reading and Writing Files
file dialog

This is documentation for Classic VPython (VPython 6), which continues to be available but is no longer supported. See vpython.org for information on installing VPython 7 or using GlowScript VPython. Documentation is available at glowscript.org by clicking Help.

A file dialog package is provided in the module visual.filedialog.

Here is how to get a file dialog display to choose a file to read, and then display the contents. The get_file() routine lets you choose a file, and it returns a file descriptor, a pointer to the chosen file (here the file descriptor has been named fd). If you cancel the file dialog display, get_file() returns None, which you should check for; the statements just after the "if fd:" will be executed only if fd is not None. Using the file descriptor you can read the entire file as one long string, or with readlines() you can read a list of lines of text, each ending with an end-of-line character ('\n').

from visual import * # must import visual or vis first
from visual.filedialog import get_file
fd = get_file()
if fd:
    data = fd.read() # or fd.readlines()
    fd.close() # close the file (we're through with it)

To choose a file and write data to the chosen file, do this:

from visual import * # must import visual or vis first
from visual.filedialog import save_file
fd = save_file()
if fd:
    fd.write("This is a test.\nThis is only a test.")
    fd.close() # close the file (we're through with it)

There are other file descriptor functions besides read(), readlines(), write(), and close(); see Python documentation. For example, fd.name is the name of the file associated with the file descriptor.

The examples shown above are sufficient for many tasks, but you can customize the file dialog display by specifying what kinds of files will be displayed in the file dialogs like this:

filter = "Python source|*.py"

With this filter specification, the only files displayed are .py files. The asterisk (*) is a "wild card" standing for "any text". (The filter option does not work on some versions of Linux.)

Here are other examples of filter expressions:

"Text files|*.txt" # show only text files
"All files|*.*"    # show all types of files
"Python and text|*.py;*.txt" # show both kinds of files
"Python|*.py|Text|*.txt" # choose which kind to list

With the following filter specification, the menu lets you choose one or the other sets of files:

"Python|*.py|Text|*.txt" # choose which kind to list

In all of these filter expressions, what you place before the "|" character will be displayed to the user (and if there is more than one, the user can choose). What goes after the "|" character is a list separated by semicolons of the file types to be displayed.