We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error closing: 'NoneType' object has no attribute 'close' for ImageNet reading
When loading ImageNet, I get the following debug messages
`Error closing: 'NoneType' object has no attribute 'close' for ImageNet reading`
message called from https://github.com/pytorch/vision/blob/45dab0e4528333332f07ab1979e006857563cf99/torchvision/datasets/folder.py#L46

caused by
https://github.com/python-pillow/Pillow/blob/7d8c0d9e39d5ed79ea6aa590b9cbff5b0d17248c/PIL/Image.py#L573

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `torchvision/datasets/folder.py`
Content:
```
1 import torch.utils.data as data
2 
3 from PIL import Image
4 import os
5 import os.path
6 
7 IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']
8 
9 
10 def is_image_file(filename):
11     """Checks if a file is an image.
12 
13     Args:
14         filename (string): path to a file
15 
16     Returns:
17         bool: True if the filename ends with a known image extension
18     """
19     filename_lower = filename.lower()
20     return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)
21 
22 
23 def find_classes(dir):
24     classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
25     classes.sort()
26     class_to_idx = {classes[i]: i for i in range(len(classes))}
27     return classes, class_to_idx
28 
29 
30 def make_dataset(dir, class_to_idx):
31     images = []
32     dir = os.path.expanduser(dir)
33     for target in sorted(os.listdir(dir)):
34         d = os.path.join(dir, target)
35         if not os.path.isdir(d):
36             continue
37 
38         for root, _, fnames in sorted(os.walk(d)):
39             for fname in sorted(fnames):
40                 if is_image_file(fname):
41                     path = os.path.join(root, fname)
42                     item = (path, class_to_idx[target])
43                     images.append(item)
44 
45     return images
46 
47 
48 def pil_loader(path):
49     # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
50     with open(path, 'rb') as f:
51         with Image.open(f) as img:
52             return img.convert('RGB')
53 
54 
55 def accimage_loader(path):
56     import accimage
57     try:
58         return accimage.Image(path)
59     except IOError:
60         # Potentially a decoding problem, fall back to PIL.Image
61         return pil_loader(path)
62 
63 
64 def default_loader(path):
65     from torchvision import get_image_backend
66     if get_image_backend() == 'accimage':
67         return accimage_loader(path)
68     else:
69         return pil_loader(path)
70 
71 
72 class ImageFolder(data.Dataset):
73     """A generic data loader where the images are arranged in this way: ::
74 
75         root/dog/xxx.png
76         root/dog/xxy.png
77         root/dog/xxz.png
78 
79         root/cat/123.png
80         root/cat/nsdf3.png
81         root/cat/asd932_.png
82 
83     Args:
84         root (string): Root directory path.
85         transform (callable, optional): A function/transform that  takes in an PIL image
86             and returns a transformed version. E.g, ``transforms.RandomCrop``
87         target_transform (callable, optional): A function/transform that takes in the
88             target and transforms it.
89         loader (callable, optional): A function to load an image given its path.
90 
91      Attributes:
92         classes (list): List of the class names.
93         class_to_idx (dict): Dict with items (class_name, class_index).
94         imgs (list): List of (image path, class_index) tuples
95     """
96 
97     def __init__(self, root, transform=None, target_transform=None,
98                  loader=default_loader):
99         classes, class_to_idx = find_classes(root)
100         imgs = make_dataset(root, class_to_idx)
101         if len(imgs) == 0:
102             raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
103                                "Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
104 
105         self.root = root
106         self.imgs = imgs
107         self.classes = classes
108         self.class_to_idx = class_to_idx
109         self.transform = transform
110         self.target_transform = target_transform
111         self.loader = loader
112 
113     def __getitem__(self, index):
114         """
115         Args:
116             index (int): Index
117 
118         Returns:
119             tuple: (image, target) where target is class_index of the target class.
120         """
121         path, target = self.imgs[index]
122         img = self.loader(path)
123         if self.transform is not None:
124             img = self.transform(img)
125         if self.target_transform is not None:
126             target = self.target_transform(target)
127 
128         return img, target
129 
130     def __len__(self):
131         return len(self.imgs)
132
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py
--- a/torchvision/datasets/folder.py
+++ b/torchvision/datasets/folder.py
@@ -48,8 +48,8 @@
 def pil_loader(path):
     # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
     with open(path, 'rb') as f:
-        with Image.open(f) as img:
-            return img.convert('RGB')
+        img = Image.open(f)
+        return img.convert('RGB')
 
 
 def accimage_loader(path):

{"golden_diff": "diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py\n--- a/torchvision/datasets/folder.py\n+++ b/torchvision/datasets/folder.py\n@@ -48,8 +48,8 @@\n def pil_loader(path):\n     # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n     with open(path, 'rb') as f:\n-        with Image.open(f) as img:\n-            return img.convert('RGB')\n+        img = Image.open(f)\n+        return img.convert('RGB')\n \n \n def accimage_loader(path):\n", "issue": "Error closing: 'NoneType' object has no attribute 'close' for ImageNet reading\nWhen loading ImageNet, I get the following debug messages\r\n`Error closing: 'NoneType' object has no attribute 'close' for ImageNet reading`\r\nmessage called from https://github.com/pytorch/vision/blob/45dab0e4528333332f07ab1979e006857563cf99/torchvision/datasets/folder.py#L46\r\n\r\ncaused by\r\nhttps://github.com/python-pillow/Pillow/blob/7d8c0d9e39d5ed79ea6aa590b9cbff5b0d17248c/PIL/Image.py#L573\n", "before_files": [{"content": "import torch.utils.data as data\n\nfrom PIL import Image\nimport os\nimport os.path\n\nIMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']\n\n\ndef is_image_file(filename):\n    \"\"\"Checks if a file is an image.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    filename_lower = filename.lower()\n    return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)\n\n\ndef find_classes(dir):\n    classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n    classes.sort()\n    class_to_idx = {classes[i]: i for i in range(len(classes))}\n    return classes, class_to_idx\n\n\ndef make_dataset(dir, class_to_idx):\n    images = []\n    dir = os.path.expanduser(dir)\n    for target in sorted(os.listdir(dir)):\n        d = os.path.join(dir, target)\n        if not os.path.isdir(d):\n            continue\n\n        for root, _, fnames in sorted(os.walk(d)):\n            for fname in sorted(fnames):\n                if is_image_file(fname):\n                    path = os.path.join(root, fname)\n                    item = (path, class_to_idx[target])\n                    images.append(item)\n\n    return images\n\n\ndef pil_loader(path):\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        with Image.open(f) as img:\n            return img.convert('RGB')\n\n\ndef accimage_loader(path):\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path):\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(data.Dataset):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n\n     Attributes:\n        classes (list): List of the class names.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(self, root, transform=None, target_transform=None,\n                 loader=default_loader):\n        classes, class_to_idx = find_classes(root)\n        imgs = make_dataset(root, class_to_idx)\n        if len(imgs) == 0:\n            raise(RuntimeError(\"Found 0 images in subfolders of: \" + root + \"\\n\"\n                               \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n\n        self.root = root\n        self.imgs = imgs\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.transform = transform\n        self.target_transform = target_transform\n        self.loader = loader\n\n    def __getitem__(self, index):\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (image, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.imgs[index]\n        img = self.loader(path)\n        if self.transform is not None:\n            img = self.transform(img)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return img, target\n\n    def __len__(self):\n        return len(self.imgs)\n", "path": "torchvision/datasets/folder.py"}], "after_files": [{"content": "import torch.utils.data as data\n\nfrom PIL import Image\nimport os\nimport os.path\n\nIMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']\n\n\ndef is_image_file(filename):\n    \"\"\"Checks if a file is an image.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    filename_lower = filename.lower()\n    return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)\n\n\ndef find_classes(dir):\n    classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n    classes.sort()\n    class_to_idx = {classes[i]: i for i in range(len(classes))}\n    return classes, class_to_idx\n\n\ndef make_dataset(dir, class_to_idx):\n    images = []\n    dir = os.path.expanduser(dir)\n    for target in sorted(os.listdir(dir)):\n        d = os.path.join(dir, target)\n        if not os.path.isdir(d):\n            continue\n\n        for root, _, fnames in sorted(os.walk(d)):\n            for fname in sorted(fnames):\n                if is_image_file(fname):\n                    path = os.path.join(root, fname)\n                    item = (path, class_to_idx[target])\n                    images.append(item)\n\n    return images\n\n\ndef pil_loader(path):\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        img = Image.open(f)\n        return img.convert('RGB')\n\n\ndef accimage_loader(path):\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path):\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(data.Dataset):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n\n     Attributes:\n        classes (list): List of the class names.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(self, root, transform=None, target_transform=None,\n                 loader=default_loader):\n        classes, class_to_idx = find_classes(root)\n        imgs = make_dataset(root, class_to_idx)\n        if len(imgs) == 0:\n            raise(RuntimeError(\"Found 0 images in subfolders of: \" + root + \"\\n\"\n                               \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n\n        self.root = root\n        self.imgs = imgs\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.transform = transform\n        self.target_transform = target_transform\n        self.loader = loader\n\n    def __getitem__(self, index):\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (image, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.imgs[index]\n        img = self.loader(path)\n        if self.transform is not None:\n            img = self.transform(img)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return img, target\n\n    def __len__(self):\n        return len(self.imgs)\n", "path": "torchvision/datasets/folder.py"}]}