Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [TOC]
- # writing file
- ## using pickle
- ```python
- try:
- f = open(pickle_file, 'wb')
- save = {
- 'train_dataset': train_dataset,
- 'train_labels': train_labels,
- 'valid_dataset': valid_dataset,
- 'valid_labels': valid_labels,
- 'test_dataset': test_dataset,
- 'test_labels': test_labels,
- }
- pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)
- f.close()
- except Exception as e:
- print('Unable to save data to', pickle_file, ':', e)
- raise
- ```
- ## write to file
- ```python
- f = open('myfile','w')
- f.write('hi there\n') # python will convert \n to os.linesep
- f.close() # you can omit in most cases as the destructor will call it
- ```
- ## file name
- ```python
- if not os.path.exists(filename):
- ```
- ## get file info
- ```python
- statinfo = os.stat(filename)
- ```
- ## concat directory + file name
- ```python
- image_file = os.path.join(folder, image)
- ```
- ## list all files
- ```python
- files = os.listdir(folder)
- ```
- ## list all directories
- ```python
- data_folders = [
- os.path.join(root, d) for d in sorted(os.listdir(root))
- if os.path.isdir(os.path.join(root, d))]
- ```
- ## directory
- ```python
- if os.path.isdir(root)
- ```
- ## file size differs
- ```python
- if statinfo.st_size == expected_bytes:
- print('Found and verified', filename)
- else:
- raise Exception(
- 'Failed to verify ' + filename + '. Can you get to it with a browser?')
- return filename
- ```
- ## extract zip files
- ```python
- zip_ref = zipfile.ZipFile(path_to_zip_file, 'r')
- zip_ref.extractall(directory_to_extract_to) # only if destiation directory is different
- zip_ref.close()
- ```
- ## extract tar files
- ```python
- tar = tarfile.open(filename)
- sys.stdout.flush()
- tar.extractall()
- tar.close()
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement