Home

If you're new to Python
and VPython: Introduction

A VPython tutorial

Pictures of 3D objects

Choose a 3D object:

Work with 3D objects:

Windows, Events, & Files:

Vector operations

Graphs

factorial/combin

What's new in Visual 5

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

 
Reading and Writing Files
file dialog

A simple 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.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.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 parameters for the get_file() and save_file() functions, as shown here with their default values:

save_file(file_extensions=None, x=100, y=100,
          title="Save", mode='w', maxfiles=20)

get_file(file_extensions=None, x=100, y=100,
          title="Open", mode='rU', maxfiles=20)

For example, get_file(file_extensions=['.txt.', '.py']) will display only files ending in these extensions. The parameter maxfiles specifies the maximum number of files to show on one page, which determines the height of the file dialog display. The default "universal" file reading mode is 'rU' which converts different kinds of end-of-line markers for Windows, Mac, and Linux files to the same standard character '\n'. The parameters x and y specify the pixel location of the upper left corner of the file dialog display, measured from the upper left corner of the computer screen. The title is displayed at the top of the window.