Skip to content

add a way to read data files from local path #451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions torchvision/datasets/mnist.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,20 @@ class MNIST(data.Dataset):
training_file = 'training.pt'
test_file = 'test.pt'

def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
def __init__(self, root, train=True, transform=None, target_transform=None,
download=False, from_local=False):

This comment was marked as off-topic.

self.root = os.path.expanduser(root)
self.transform = transform
self.target_transform = target_transform
self.train = train # training set or test set
self.from_local = from_local

if download:
self.download()

elif self.from_local:

This comment was marked as off-topic.

self.download()

if not self._check_exists():
raise RuntimeError('Dataset not found.' +
' You can use download=True to download it')
Expand Down Expand Up @@ -95,6 +100,7 @@ def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
from six.moves import urllib
import gzip
import shutil

if self._check_exists():
return
Expand All @@ -110,12 +116,18 @@ def download(self):
raise

for url in self.urls:
print('Downloading ' + url)
data = urllib.request.urlopen(url)
filename = url.rpartition('/')[2]
file_path = os.path.join(self.root, self.raw_folder, filename)
with open(file_path, 'wb') as f:
f.write(data.read())

if self.from_local:
tmp_file_path = os.path.join(self.root, filename)
shutil.move(tmp_file_path, os.path.join(self.root, self.raw_folder))
else:
print('Downloading ' + url)
data = urllib.request.urlopen(url)
with open(file_path, 'wb') as f:
f.write(data.read())

with open(file_path.replace('.gz', ''), 'wb') as out_f, \
gzip.GzipFile(file_path) as zip_f:
out_f.write(zip_f.read())
Expand Down