@@ -29,7 +29,7 @@ def test_sanity():
         f.close()
         sin = file("onlyread.tmp", "r")
         sout = file("onlywrite.tmp", "w")
-        
+
         # writer is null for sin
         AssertError(IOError, sin.write, "abc")
         AssertError(IOError, sin.writelines, ["abc","def"])
@@ -42,7 +42,7 @@ def test_sanity():
             AssertError(IOError, sout.readline, 10)
             AssertError(IOError, sout.readlines)
             AssertError(IOError, sout.readlines, 10)
-        
+
         sin.close()
         sout.close()
 
@@ -98,42 +98,36 @@ def randbyte():
         data += chr(randbyte())
 
     # Keep a copy of the data safe.
-    orig_data = data;
+    orig_data = data
 
     # Write the data to disk in binary mode.
-    f = file(temp_file, "wb")
-    f.write(data)
-    f.close()
+    with file(temp_file, "wb") as f:
+        f.write(data)
 
     # And read it back in again.
-    f = file(temp_file, "rb")
-    data = f.read()
-    f.close()
+    with file(temp_file, "rb") as f:
+        data = f.read()
 
     # Check nothing changed.
     Assert(data == orig_data)
     
 def test_cp10983():
     # writing non-unicode characters > 127 should be preserved
-    x = open(temp_file, 'w')
-    x.write('\xa33')
-    x.close()
-    
-    x = open(temp_file)
-    data = x.read()
-    x.close()
-    
+    with open(temp_file, 'w') as x:
+        x.write('\xa33')
+
+    with open(temp_file) as x:
+        data = x.read()
+
     AreEqual(ord(data[0]), 163)
     AreEqual(ord(data[1]), 51)
-    
-    x = open(temp_file, 'w')
-    x.write("a2\xa33\u0163\x0F\x0FF\t\\\x0FF\x0FE\x00\x01\x7F\x7E\x80")
-    x.close()
-    
-    x = open(temp_file)
-    data = x.read()
-    x.close()
-    
+
+    with open(temp_file, 'w') as x:
+        x.write("a2\xa33\u0163\x0F\x0FF\t\\\x0FF\x0FE\x00\x01\x7F\x7E\x80")
+
+    with open(temp_file) as x:
+        data = x.read()
+
     AreEqual(data, 'a2\xa33\\u0163\x0f\x0fF\t\\\x0fF\x0fE\x00\x01\x7F\x7E\x80')
 
 @skip('win32')
@@ -142,15 +136,13 @@ def test_cp27179():
     from System import Array, Byte
     data_string = 'abcdef\nghijkl\n\n'
     data = Array[Byte](map(Byte, map(ord, data_string)))
-    
-    f = open(temp_file, 'w+')
-    f.write(data)
-    f.close()
-    
-    f = open(temp_file, 'r')
-    data_read = f.read()
-    f.close()
-    
+
+    with open(temp_file, 'w+') as f:
+        f.write(data)
+
+    with open(temp_file, 'r') as f:
+        data_read = f.read()
+
     AreEqual(data_string, data_read)
 
 # Helper used to format newline characters into a visible format.
@@ -177,6 +169,7 @@ def format_newlines(string):
 # The following is the setup for a set of pattern mode tests that will check
 # some tricky edge cases for newline translation for both reading and writing.
 # The entry point is the test_patterns() function.
+@skip("posix") # posix doesn't do any newline translation if b is specified, so this test is invalid
 def test_newlines():
 
     # Read mode test cases. Each tuple has three values; the raw on-disk value we
@@ -216,42 +209,38 @@ def test_newlines():
     def test_read_pattern(pattern):
         # Write the initial data to disk using binary mode (we test this
         # functionality earlier so we're satisfied it gets there unaltered).
-        f = file(temp_file, "wb")
-        f.write(pattern[0])
-        f.close()
+        with file(temp_file, "wb") as f:
+            f.write(pattern[0])
 
         # Read the data back in each read mode, checking that we get the correct
         # transform each time.
         for mode in range(3):
-            test_read_mode(pattern, mode);
+            test_read_mode(pattern, mode)
 
     # Test a specific read mode pattern for a given reading mode.
     def test_read_mode(pattern, mode):
         # Read the data back from disk using the given read mode.
-        f = file(temp_file, read_modes[mode][1])
-        contents = f.read()
-        f.close()
+        with file(temp_file, read_modes[mode][1]) as f:
+            contents = f.read()
 
         # Check it equals what we expected for this mode.
         Assert(contents == pattern[mode])
 
     # Test a specific write mode pattern.
     def test_write_pattern(pattern):
         for mode in range(2):
-            test_write_mode(pattern, mode);
+            test_write_mode(pattern, mode)
 
     # Test a specific write mode pattern for a given write mode.
     def test_write_mode(pattern, mode):
         # Write the raw data using the given mode.
-        f = file(temp_file, write_modes[mode][1])
-        f.write(pattern[0])
-        f.close()
+        with file(temp_file, write_modes[mode][1]) as f:
+            f.write(pattern[0])
 
         # Read the data back in using binary mode (we tested this gets us back
         # unaltered data earlier).
-        f = file(temp_file, "rb")
-        contents = f.read()
-        f.close()
+        with file(temp_file, "rb") as f:
+            contents = f.read()
 
         # Check it equals what we expected for this mode.
         Assert(contents == pattern[mode])
@@ -269,94 +258,105 @@ def test_patterns():
 # Now some tests of read(size).
 # Test data is in the following format: ("raw data", read_size, (binary mode result strings) (binary mode result tell() result)
 #                                                               (text mode result strings) (text mode result tell() result)
-#                                                               (universal mode result strings) (univermose mode result tell() results)
+#                                                               (universal mode result strings) (universal mode result tell() results)
 
 def test_read_size():
-    read_size_tests = (("Hello", 1, ("H", "e", "l", "l", "o"), (1,2,3,4,5),
+    read_size_tests = [("Hello", 1, ("H", "e", "l", "l", "o"), (1,2,3,4,5),
                                     ("H", "e", "l", "l", "o"), (1,2,3,4,5),
                                     ("H", "e", "l", "l", "o"), (1,2,3,4,5)),
                        ("Hello", 2, ("He", "ll", "o"), (2,4,5),
                                     ("He", "ll", "o"), (2,4,5),
-                                    ("He", "ll", "o"), (2,4,5)),
-                       ("H\re\n\r\nllo", 1, ("H", "\r", "e", "\n", "\r", "\n", "l", "l", "o"), (1,2,3,4,5,6,7, 8, 9),
+                                    ("He", "ll", "o"), (2,4,5))]
+
+    if is_posix:
+        read_size_tests.append(("H\re\n\r\nllo", 1, ("H", "\r", "e", "\n", "\r", "\n", "l", "l", "o"), (1,2,3,4,5,6,7, 8, 9),
+                                            ("H", "\r", "e", "\n", "\r", "\n", "l", "l", "o"), (1, 2, 3, 4, 5, 6, 7, 8, 9),
+                                            ("H", "\n", "e", "\n", "\n", "l", "l", "o"), (1, 2, 3, 4, 6, 7, 8, 9)))
+        read_size_tests.append(("H\re\n\r\nllo", 2, ("H\r", "e\n", "\r\n", "ll", "o"), (2, 4, 6, 8, 9),
+                                            ("H\r", "e\n", "\r\n", "ll", "o"), (2, 4, 6, 8, 9),
+                                            ("H\n", "e\n", "\nl", "lo"), (2, 4, 7, 9)))
+    else:
+         read_size_tests.append(("H\re\n\r\nllo", 1, ("H", "\r", "e", "\n", "\r", "\n", "l", "l", "o"), (1,2,3,4,5,6,7, 8, 9),
                                             ("H", "\r", "e", "\n", "\n", "l", "l", "o"), (1,2,3,4,6,7,8,9),
-                                            ("H", "\n", "e", "\n", "\n", "l", "l", "o"), (1,2,3,4,6,7,8,9)),
-                       ("H\re\n\r\nllo", 2, ("H\r", "e\n", "\r\n", "ll", "o"), (2, 4, 6, 8, 9),
+                                            ("H", "\n", "e", "\n", "\n", "l", "l", "o"), (1,2,3,4,6,7,8,9)))
+         read_size_tests.append(("H\re\n\r\nllo", 2, ("H\r", "e\n", "\r\n", "ll", "o"), (2, 4, 6, 8, 9),
                                             ("H\r", "e\n", "\nl", "lo"), (2,4,7, 9),
                                             ("H\n", "e\n", "\nl", "lo"), (2,4,7, 9)))
 
     if not is_cli: return
     
     for test in read_size_tests:
         # Write the test pattern to disk in binary mode.
-        f = file(temp_file, "wb")
-        f.write(test[0])
-        f.close()
+        with file(temp_file, "wb") as f:
+            f.write(test[0])
 
         # Read the data back in each of the read modes we test.
         for mode in range(3):
-            f = file(temp_file, read_modes[mode][1])
-            AreEqual(f.closed, False)
-
-            # We read the data in the size specified by the test and expect to get
-            # the set of strings given for this specific mode.
-            size = test[1]
-            strings = test[2 + mode*2]
-            lengths = test[3 + mode*2]
-            count = 0
-            while True:
-                data = f.read(size)
-                if data == "":
-                    Assert(count == len(strings))
-                    break
-                count = count + 1
-                Assert(count <= len(strings))
-                Assert(data == strings[count - 1])
-                AreEqual(f.tell(), lengths[count-1])
-
-            f.close()
-            AreEqual(f.closed, True)
+            with file(temp_file, read_modes[mode][1]) as f:
+                AreEqual(f.closed, False)
+
+                # We read the data in the size specified by the test and expect to get
+                # the set of strings given for this specific mode.
+                size = test[1]
+                strings = test[2 + mode*2]
+                lengths = test[3 + mode*2]
+                count = 0
+                while True:
+                    data = f.read(size)
+                    if data == "":
+                        Assert(count == len(strings))
+                        break
+                    count = count + 1
+                    Assert(count <= len(strings))
+                    Assert(data == strings[count - 1])
+                    AreEqual(f.tell(), lengths[count-1])
+                f.close()
+                AreEqual(f.closed, True)
 
 # And some readline tests.
 # Test data is in the following format: ("raw data", (binary mode result strings)
 #                                                    (text mode result strings)
 #                                                    (universal mode result strings))
 def test_readline():
-    readline_tests = (("Mary had a little lamb", ("Mary had a little lamb", ),
+    readline_tests = [("Mary had a little lamb", ("Mary had a little lamb", ),
                                                  ("Mary had a little lamb", ),
                                                  ("Mary had a little lamb", )),
                       ("Mary had a little lamb\r", ("Mary had a little lamb\r", ),
                                                    ("Mary had a little lamb\r", ),
                                                    ("Mary had a little lamb\n", )),
                       ("Mary had a \rlittle lamb\r", ("Mary had a \rlittle lamb\r", ),
                                                      ("Mary had a \rlittle lamb\r", ),
-                                                     ("Mary had a \n", "little lamb\n")),
-                      ("Mary \r\nhad \na little lamb", ("Mary \r\n", "had \n", "a little lamb"),
+                                                     ("Mary had a \n", "little lamb\n"))]
+
+    # wb doesn't change the output to just \n like on Windows (binary mode means nothing on POSIX)
+    if is_posix:
+        readline_tests.append(("Mary \r\nhad \na little lamb", ("Mary \r\n", "had \n", "a little lamb"),
+                                                       ("Mary \r\n", "had \n", "a little lamb"),
+                                                       ("Mary \n", "had \n", "a little lamb")))
+    else:
+        readline_tests.append(("Mary \r\nhad \na little lamb", ("Mary \r\n", "had \n", "a little lamb"),
                                                        ("Mary \n", "had \n", "a little lamb"),
                                                        ("Mary \n", "had \n", "a little lamb")))
     for test in readline_tests:
         # Write the test pattern to disk in binary mode.
-        f = file(temp_file, "wb")
-        f.write(test[0])
-        f.close()
+        with file(temp_file, "wb") as f:
+            f.write(test[0])
 
         # Read the data back in each of the read modes we test.
         for mode in range(3):
-            f = file(temp_file, read_modes[mode][1])
-
-            # We read the data by line and expect to get a specific sets of lines back.
-            strings = test[1 + mode]
-            count = 0
-            while True:
-                data = f.readline()
-                if data == "":
-                    AreEqual(count, len(strings))
-                    break
-                count = count + 1
-                Assert(count <= len(strings))
-                AreEqual(data, strings[count - 1])
+            with file(temp_file, read_modes[mode][1]) as f:
+                # We read the data by line and expect to get a specific sets of lines back.
+                strings = test[1 + mode]
+                count = 0
+                while True:
+                    data = f.readline()
+                    if data == "":
+                        AreEqual(count, len(strings))
+                        break
+                    count = count + 1
+                    Assert(count <= len(strings))
+                    AreEqual(data, strings[count - 1])
 
-            f.close()
 
 def format_tuple(tup):
     if tup == None:
@@ -385,94 +385,91 @@ def test_newlines_attribute():
     
     for test in newlines_tests:
         # Write the test pattern to disk in binary mode.
-        f = file(temp_file, "wb")
-        f.write(test[0])
-        # Verify newlines isn't set while writing.
-        Assert(f.newlines == None)
-        f.close()
+        with file(temp_file, "wb") as f:
+            f.write(test[0])
+            # Verify newlines isn't set while writing.
+            Assert(f.newlines == None)
 
         # Verify that reading the file in binary or text mode won't set newlines.
-        f = file(temp_file, "rb")
-        data = f.read()
-        Assert(f.newlines == None)
-        f.close()
+        with file(temp_file, "rb") as f:
+            data = f.read()
+            Assert(f.newlines == None)
 
-        f = file(temp_file, "r")
-        data = f.read()
-        Assert(f.newlines == None)
-        f.close()
+        with file(temp_file, "r") as f:
+            data = f.read()
+            Assert(f.newlines == None)
 
         # Read file in universal mode line by line and verify we see the expected output at each stage.
         expected = test[1]
-        f = file(temp_file, "rU")
-        Assert(f.newlines == None)
-        count = 0
-        while True:
-            data = f.readline()
-            if data == "":
-                break
-            Assert(count < len(expected))
-            Assert(f.newlines == expected[count])
-            count = count + 1
-        f.close()
-    
+        with file(temp_file, "rU") as f:
+            Assert(f.newlines == None)
+            count = 0
+            while True:
+                data = f.readline()
+                if data == "":
+                    break
+                Assert(count < len(expected))
+                Assert(f.newlines == expected[count])
+                count = count + 1
+
+
 ## coverage: a sequence of file operation
 @skip("posix")
 def test_coverage():
-    f = file(temp_file, 'w')
-    Assert(str(f).startswith("<open file '%s', mode 'w'" % temp_file))
-    Assert(f.fileno() <> -1)
-    Assert(f.fileno() <> 0)
+    with file(temp_file, 'w') as f:
+        Assert(str(f).startswith("<open file '%s', mode 'w'" % temp_file))
+        Assert(f.fileno() <> -1)
+        Assert(f.fileno() <> 0)
 
-    # write
-    AssertError(TypeError, f.writelines, [3])
-    f.writelines(["firstline\n"])
+        # write
+        AssertError(TypeError, f.writelines, [3])
+        f.writelines(["firstline\n"])
 
     f.close()
     Assert(str(f).startswith("<closed file '%s', mode 'w'" % temp_file))
 
     # append
-    f = file(temp_file, 'a+')
-    f.writelines(['\n', 'secondline\n'])
+    with file(temp_file, 'a+') as f:
+        f.writelines(['\n', 'secondline\n'])
 
-    pos = len('secondline\n') + 1
-    f.seek(-1 * pos, 1)
+        pos = len('secondline\n') + 1
+        f.seek(-1 * pos, 1)
 
-    f.writelines(['thirdline\n'])
-    f.close()
+        f.writelines(['thirdline\n'])
 
     # read
-    f = file(temp_file, 'r+', 512)
-    f.seek(-1 * pos - 2, 2)
-    AreEqual(f.readline(), 'e\n')
-    AreEqual(f.readline(5), 'third')
-    AreEqual(f.read(-1), 'line\n')
-    AreEqual(f.read(-1), '')
-    f.close()
+    with file(temp_file, 'r+', 512) as f:
+        f.seek(-1 * pos - 2, 2)
+        AreEqual(f.readline(), 'e\n')
+        AreEqual(f.readline(5), 'third')
+        AreEqual(f.read(-1), 'line\n')
+        AreEqual(f.read(-1), '')
 
     # read
-    f = file(temp_file, 'rb', 512)
-    f.seek(-1 * pos - 2, 2)
-    AreEqual(f.readline(), 'e\r\n')
-    AreEqual(f.readline(5), 'third')
-    AreEqual(f.read(-1), 'line\r\n')
-    AreEqual(f.read(-1), '')
-    f.close()
+    with file(temp_file, 'rb', 512) as f:
+        f.seek(-1 * pos - 2, 2)
+        AreEqual(f.readline(), 'e\r\n')
+        AreEqual(f.readline(5), 'third')
+        AreEqual(f.read(-1), 'line\r\n')
+        AreEqual(f.read(-1), '')
 
     ## file op in os
     os.unlink(temp_file)
 
     fd = os.open(temp_file, os.O_CREAT | os.O_WRONLY)
-    os.write(fd, "hello ")
-    os.close(fd)
+    try:
+        os.write(fd, "hello ")
+        os.close(fd)
 
-    fd = os.open(temp_file, os.O_APPEND | os.O_WRONLY)
-    os.write(fd, "world")
-    os.close(fd)
+        fd = os.open(temp_file, os.O_APPEND | os.O_WRONLY)
+        os.write(fd, "world")
+        os.close(fd)
 
-    fd = os.open(temp_file, 0)
-    AreEqual(os.read(fd, 1024), "hello world")
-    os.close(fd)
+        fd = os.open(temp_file, 0)
+        AreEqual(os.read(fd, 1024), "hello world")
+        os.close(fd)
+    finally:
+        os.close(fd)
 
     os.unlink(temp_file)
 
@@ -495,13 +492,11 @@ def test_encoding():
         saved = sys.getdefaultencoding()
         try:
             setenc('utf8')
-            f = file(temp_file, 'w')
-            f.write(u'\u6211')
-            f.close()
+            with file(temp_file, 'w') as f:
+                f.write(u'\u6211')
 
-            f = file(temp_file, 'r')
-            txt = f.read()
-            f.close()
+            with file(temp_file, 'r') as f:
+                txt = f.read()
             AreEqual(txt, u'\u6211')
         finally:
             setenc(saved)
@@ -513,19 +508,17 @@ def test_net_stream():
             import clr
             clr.AddReference("System.IO.FileSystem")
             clr.AddReference("System.IO.FileSystem.Primitives")
-        fs = System.IO.FileStream(temp_file, System.IO.FileMode.Create, System.IO.FileAccess.Write)
-        f = file(fs, "wb")
-        f.write('hello\rworld\ngoodbye\r\n')
-        f.close()
-        
-        f = file(temp_file, 'rb')
-        AreEqual(f.read(), 'hello\rworld\ngoodbye\r\n')
-        f.close()
+
+        fs = System.IO.FileStream(temp_file, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
+        with file(fs, "wb") as f:
+            f.write('hello\rworld\ngoodbye\r\n')
         
-        f = file(temp_file, 'rU')
-        AreEqual(f.read(), 'hello\nworld\ngoodbye\n')
-        f.close()
-    
+        with file(temp_file, 'rb') as f:
+            AreEqual(f.read(), 'hello\rworld\ngoodbye\r\n')
+
+        with file(temp_file, 'rU') as f:
+            AreEqual(f.read(), 'hello\nworld\ngoodbye\n')
+
     def test_file_manager():
         def return_fd1():
             f = file(temp_file, 'w')
@@ -590,6 +583,7 @@ def __init__(self,fname,VERBOSITY=0):
     os.unlink('sometext.txt')
 
 # file newline handling test
+@skip("posix") # this test doesn't really make sense for posix since b doesn't change the behavior
 def test_newline():
     def test_newline(norm, mode):
         f = file("testfile.tmp", mode)
@@ -636,43 +630,37 @@ def __repr__(self): return 'abc'
 def test_truncate():
     
     # truncate()
-    a = file('abc.txt', 'w')
-    a.write('hello world\n')
-    a.truncate()
-    a.close()
+    with file('abc.txt', 'w') as a:
+        a.write('hello world\n')
+        a.truncate()
+
+    with file('abc.txt', 'r') as a:
+        AreEqual(a.readlines(), ['hello world\n'])
     
-    a = file('abc.txt', 'r')
-    AreEqual(a.readlines(), ['hello world\n'])
-    a.close()
     os.unlink('abc.txt')
 
     # truncate(#)
-    a = file('abc.txt', 'w')
-    a.write('hello\nworld\n')
-    a.truncate(6)
-    a.close()
+    with file('abc.txt', 'w') as a:
+        a.write('hello\nworld\n')
+        a.truncate(6)
     
-    a = file('abc.txt', 'r')
-    if is_posix:
-        AreEqual(a.readlines(), ['hello\n'])
-    else:
-        AreEqual(a.readlines(), ['hello\r'])
-    a.close()
+    with file('abc.txt', 'r') as a:
+        if is_posix:
+            AreEqual(a.readlines(), ['hello\n'])
+        else:
+            AreEqual(a.readlines(), ['hello\r'])
 
     os.unlink('abc.txt')
     
     # truncate(#) invalid args
-    a = file('abc.txt', 'w')
-    AssertError(IOError, a.truncate, -1)
-    AssertError(TypeError, a.truncate, None)
-    a.close()
+    with file('abc.txt', 'w') as a:
+        AssertError(IOError, a.truncate, -1)
+        AssertError(TypeError, a.truncate, None)
     
     # read-only file
-    a = file('abc.txt', 'r')
-    AssertError(IOError, a.truncate)
-    AssertError(IOError, a.truncate, 0)
-    a.close()
-    
+    with file('abc.txt', 'r') as a:
+        AssertError(IOError, a.truncate)
+        AssertError(IOError, a.truncate, 0)
     os.unlink('abc.txt')
     
     # std-out
@@ -681,9 +669,8 @@ def test_truncate():
 def test_modes():
     """test various strange mode combinations and error reporting"""
     try:
-        x = file('test_file', 'w')
-        AreEqual(x.mode, 'w')
-        x.close()
+        with file('test_file', 'w') as x:
+            AreEqual(x.mode, 'w')
         # don't allow empty modes
         AssertErrorWithMessage(ValueError, 'empty mode string', file, 'abc', '')
         
@@ -720,34 +707,31 @@ def test_cp16623():
     expected_lines = ["a", "bbb" * 100, "cc"]
     total_threads = 50
     file_name = path_combine(testpath.temporary_dir, "cp16623.txt")
-    f = open(file_name, "w")
-    
-    def write_stuff():
-        global FINISHED_COUNTER
-        global CP16623_LOCK
-        for j in xrange(100):
-            for i in xrange(50):
-                print >> f, "a"
-            print >> f, "bbb" * 1000
-            for i in xrange(10):
-                print >> f, "cc"
+    with open(file_name, "w") as f:
         
-        with CP16623_LOCK:
-            FINISHED_COUNTER += 1
-
-    for i in xrange(total_threads):
-        thread.start_new_thread(write_stuff, ())
-
-    #Give all threads some time to finish
-    for i in xrange(total_threads):
-        if FINISHED_COUNTER!=total_threads:
-            print "*",
-            time.sleep(1)
-        else:
-            break
-    AreEqual(FINISHED_COUNTER, total_threads)    
-    f.close()
-    
+        def write_stuff():
+            global FINISHED_COUNTER
+            global CP16623_LOCK
+            for j in xrange(100):
+                for i in xrange(50):
+                    print >> f, "a"
+                print >> f, "bbb" * 1000
+                for i in xrange(10):
+                    print >> f, "cc"
+            with CP16623_LOCK:
+                FINISHED_COUNTER += 1
+
+        for i in xrange(total_threads):
+            thread.start_new_thread(write_stuff, ())
+
+        #Give all threads some time to finish
+        for i in xrange(total_threads):
+            if FINISHED_COUNTER!=total_threads:
+                print "*",
+                time.sleep(1)
+            else:
+                break
+        AreEqual(FINISHED_COUNTER, total_threads)
     #Verifications - since print isn't threadsafe the following
     #is pointless...  Just make sure IP doesn't throw.
     #f = open(file_name, "r")
@@ -761,42 +745,36 @@ def test_write_buffer():
     
     try:
         for mode in ('b', ''):
-            foo = open('foo', 'w+' + mode)
-            b = buffer(b'hello world', 6)
-            foo.write(b)
-            foo.close()
+            with open('foo', 'w+' + mode) as foo:
+                b = buffer(b'hello world', 6)
+                foo.write(b)
         
-            foo = open('foo', 'r')
-            AreEqual(foo.readlines(), ['world'])
-            foo.close()
+            with open('foo', 'r') as foo:
+                AreEqual(foo.readlines(), ['world'])
         
-        foo = open('foo', 'w+')
-        b = buffer(u'hello world', 6)
-        foo.write(b)
-        foo.close()
+        with open('foo', 'w+') as foo:
+            b = buffer(u'hello world', 6)
+            foo.write(b)
+        with open('foo', 'r') as foo:
+            AreEqual(foo.readlines(), ['world'])
         
-        foo = open('foo', 'r')
-        AreEqual(foo.readlines(), ['world'])
-        foo.close()
+        with open('foo', 'w+b') as foo:
+            b = buffer(u'hello world', 6)
+            foo.write(b)
         
-        foo = open('foo', 'w+b')
-        b = buffer(u'hello world', 6)
-        foo.write(b)
-        foo.close()
         
-        foo = open('foo', 'r')
-        if is_cpython:
-            AreEqual(foo.readlines(), ['l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'])
-        else:
-            AreEqual(foo.readlines(), ['world'])
-        foo.close()
+        with open('foo', 'r') as foo:
+            if is_cpython:
+                AreEqual(foo.readlines(), ['l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'])
+            else:
+                AreEqual(foo.readlines(), ['world'])
 
     finally:
         delete_files("foo")
 
 def test_errors():
     try:
-        file('some_file_that_really_does_not_exist')        
+        file('some_file_that_really_does_not_exist')
     except Exception, e:
         AreEqual(e.errno, 2)
     else:
@@ -818,6 +796,7 @@ def test_write_bytes():
         AreEqual(f.readlines(), ['Hello\n'])
         f.close()
     finally:
+        f.close()
         os.unlink('temp_ip')
 
 def test_kw_args():
@@ -847,11 +826,13 @@ def test_open_with_BOM():
     # gh1088
     # https://github.com/IronLanguages/main/issues/1088
     with open("file_without_BOM.txt", "r") as f:
-        AreEqual(f.read(), "\x42\xc3\x93\x4d\x0a")
+        if is_posix: AreEqual(f.read(), "\x42\xc3\x93\x4d\x0d\x0a")
+        else: AreEqual(f.read(), "\x42\xc3\x93\x4d\x0a")
     with open("file_without_BOM.txt", "rb") as f:
         AreEqual(f.read(), "\x42\xc3\x93\x4d\x0d\x0a")
     with open("file_with_BOM.txt", "r") as f:
-        AreEqual(f.read(), "\xef\xbb\xbf\x42\xc3\x93\x4d\x0a")
+        if is_posix: AreEqual(f.read(), "\xef\xbb\xbf\x42\xc3\x93\x4d\x0d\x0a")
+        else: AreEqual(f.read(), "\xef\xbb\xbf\x42\xc3\x93\x4d\x0a")
     with open("file_with_BOM.txt", "rb") as f:
         AreEqual(f.read(), "\xef\xbb\xbf\x42\xc3\x93\x4d\x0d\x0a")
 