Home

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

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)
    print(data)

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)|*.py|" \
           "Compiled Python (*.pyc)|*.pyc|" \
           "Text files (*.txt)|*.txt|" \
           "All files (*.*)|*.*"

get_file(filter)

With this filter specification, the first set of files displayed are .py files, and there is a menu that lets you choose one of the other sets of files. The asterisk (*) is a "wild card" standing for "any text". (The filter option does not work on some versions of Linux.)