Working with Files

Here are some samples of working with files in boo and .NET/Mono.

import System.IO
import System.Reflection

testfile = "newtestfile.txt"
try:
	if File.Exists(testfile):
		File.Delete(testfile)

	//"using" will dispose of (and close) the file stream for you
	using out = StreamWriter(testfile):
		out.WriteLine("  Some text for this file  ")
		out.WriteLine("# ignore this line")
		out.WriteLine("  Some more text  ")

	using input = StreamReader(testfile): //or you can use File.OpenText
		for line in input:
			line = line.Trim()
			if len(line) > 0 and line[0] != char('#'):
				print line
	
	//an example using enumerate and no "using"
	fileinput = File.OpenText(testfile)
	for index as int, line as string in enumerate(fileinput):
		print "line ${index}:", line.ToUpper()
	fileinput.Close()
	
except e:
	print "Error", e.ToString()


//An example of constructing file paths

//Assembly.GetExecutingAssembly().Location won't work in booi because you are executing a
//dynamic assembly in memory, you have to compile using booc first
rsppath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "boo.rsp")

print Path.GetFileNameWithoutExtension(rsppath)

See also:

Labels

 
(None)
  1. Aug 05, 2007

    jbryankelly says:

    ...this post originally by bamboo... TextReader is considered to be enumerable ...

    ...this post originally by bamboo...

    TextReader is considered to be enumerable in boo. So you can write things like:

    for line in File.OpenText("foo"):
    print line.ToUpper() if len(line) > 0

    Yep. Type inference works.

    I like how easy it is to grep:

    for index, line in File.OpenText("foo"):
    print "$