View this PageEdit this PageUploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

File I/O from Jython

In order to do the filesharing stuff, you'll need to be able to list the files in a directory, and then read a file into a string.

Listing files in a directory


import os
os.listdir("directory_name")

The above code returns a list of all of the filenames in the specified directory.

Reading a file


f = open("filename", "mode")
s = f.read()

The first line opens the file specified by filename, returning a file object called f in this case. The mode argument is a two-character string: the first character should be "r" for reading or "w" for writing; the second should be "t" for text or "b" for binary. For this project, you can assume I'll only test with text files, so you can just use "rt" or "r" by itself to default to text.

The second line reads the entire file into a string called s.