query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
save list to file | python | def save_list(lst, path):
"""
Save items from list to the file.
"""
with open(path, 'wb') as out:
lines = []
for item in lst:
if isinstance(item, (six.text_type, six.binary_type)):
lines.append(make_str(item))
else:
lines.append(make_str(json.dumps(item)))
out.write(b'\n'.join(lines) + b'\n') | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/script/crawl.py#L57-L69 |
save list to file | python | def save(self, filename, content):
"""
default is to save a file from list of lines
"""
with open(filename, "w") as f:
if hasattr(content, '__iter__'):
f.write('\n'.join([row for row in content]))
else:
print('WRINGI CONTWETESWREWR')
f.write(str(content)) | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L230-L239 |
save list to file | python | def save_filelist(self, opFile, opFormat, delim=',', qu='"'):
"""
uses a List of files and collects meta data on them and saves
to an text file as a list or with metadata depending on opFormat.
"""
op_folder = os.path.dirname(opFile)
if op_folder is not None: # short filename passed
if not os.path.exists(op_folder):
os.makedirs(op_folder)
with open(opFile,'w') as fout:
fout.write("fullFilename" + delim)
for colHeading in opFormat:
fout.write(colHeading + delim)
fout.write('\n')
for f in self.filelist:
line = qu + f + qu + delim
try:
for fld in opFormat:
if fld == "name":
line = line + qu + os.path.basename(f) + qu + delim
if fld == "date":
line = line + qu + self.GetDateAsString(f) + qu + delim
if fld == "size":
line = line + qu + str(os.path.getsize(f)) + qu + delim
if fld == "path":
line = line + qu + os.path.dirname(f) + qu + delim
except IOError:
line += '\n' # no metadata
try:
fout.write (str(line.encode('ascii', 'ignore').decode('utf-8')))
fout.write ('\n')
except IOError:
#print("Cant print line - cls_filelist line 304")
pass | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/lib/cls_filelist.py#L192-L228 |
save list to file | python | def save(self, list_file):
"""Saves the current list of annotations to the given file.
**Parameters:**
``list_file`` : str
The name of a list file to write the currently stored list into
"""
bob.io.base.create_directories_safe(os.path.dirname(list_file))
with open(list_file, 'w') as f:
for i in range(len(self.image_paths)):
f.write(self.image_paths[i])
for bbx in self.bounding_boxes[i]:
f.write("\t[%f %f %f %f]" % (bbx.top_f, bbx.left_f, bbx.size_f[0], bbx.size_f[1]))
f.write("\n") | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/TrainingSet.py#L79-L93 |
save list to file | python | def _save_history_to_file(history, path, size=-1):
"""Save a history list to a file for later loading (possibly in another
session).
:param history: the history list to save
:type history: list(str)
:param path: the path to the file where to save the history
:param size: the number of lines to save (0 means no lines, < 0 means
all lines)
:type size: int
:type path: str
:returns: None
"""
if size == 0:
return
if size > 0:
history = history[-size:]
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
# Write linewise to avoid building a large string in menory.
with codecs.open(path, 'w', encoding='utf-8') as histfile:
for line in history:
histfile.write(line)
histfile.write('\n') | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L773-L797 |
save list to file | python | def save_to_name_list(dest, name_parts, value):
"""
Util to save some name sequence to a dict. For instance, `("location","query")` would save
to dest["location"]["query"].
"""
if len(name_parts) > 1:
for part in name_parts[:-1]:
if part not in dest:
dest[part] = {}
dest = dest[part]
dest[name_parts[-1]] = value | https://github.com/tiffon/take/blob/907a2c4a72f5cbd357eadd4837fa4cae23647096/take/utils.py#L22-L32 |
save list to file | python | def _save_file(self, data, path):
"""Save an file to the specified path.
:param data: binary data of the file
:param path: path to save the file to
"""
with open(path, 'wb') as tfile:
for chunk in data:
tfile.write(chunk) | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmconnector/restclient.py#L1001-L1008 |
save list to file | python | def save_file(self, path=None, filters='*.dat', force_extension=None, force_overwrite=False, header_only=False, delimiter='use current', binary=None):
"""
This will save all the header info and columns to an ascii file with
the specified path.
Parameters
----------
path=None
Path for saving the data. If None, this will bring up
a save file dialog.
filters='*.dat'
File filter for the file dialog (for path=None)
force_extension=None
If set to a string, e.g., 'txt', it will enforce that the chosen
filename will have this extension.
force_overwrite=False
Normally, if the file * exists, this will copy that
to *.backup. If the backup already exists, this
function will abort. Setting this to True will
force overwriting the backup file.
header_only=False
Only output the header?
delimiter='use current'
This will set the delimiter of the output file
'use current' means use self.delimiter
binary=None
Set to one of the allowed numpy dtypes, e.g., float32, float64,
complex64, int32, etc. Setting binary=True defaults to float64.
Note if the header contains the key SPINMOB_BINARY and binary=None,
it will save as binary using the header specification.
"""
# Make sure there isn't a problem later with no-column databoxes
if len(self)==0: header_only=True
# This is the final path. We now write to a temporary file in the user
# directory, then move it to the destination. This (hopefully) fixes
# problems with sync programs.
if path in [None]: path = _s.dialogs.save(filters, default_directory=self.directory)
if path in ["", None]:
print("Aborted.")
return False
# Force the extension (we do this here redundantly, because the user may have also
# specified a path explicitly)
if not force_extension == None:
# In case the user put "*.txt" instead of just "txt"
force_extension = force_extension.replace('*','').replace('.','')
# If the file doesn't end with the extension, add it
if not _os.path.splitext(path)[-1][1:] == force_extension:
path = path + '.' + force_extension
# Save the path for future reference
self.path=path
# if the path exists, make a backup
if _os.path.exists(path) and not force_overwrite:
_os.rename(path,path+".backup")
# get the delimiter
if delimiter == "use current":
if self.delimiter is None: delimiter = "\t"
else: delimiter = self.delimiter
# figure out the temporary path
temporary_path = _os.path.join(_s.settings.path_home, "temp-"+str(int(1e3*_time.time()))+'-'+str(int(1e9*_n.random.rand(1))))
# open the temporary file
f = open(temporary_path, 'w')
# Override any existing binary if we're supposed to
if binary in [False, 'text', 'Text', 'ASCII', 'csv', 'CSV']:
self.pop_header('SPINMOB_BINARY', True)
binary = None
# If the binary flag is any kind of binary format, add the key
if not binary in [None, False, 'text', 'Text', 'ASCII', 'csv', 'CSV']:
self.h(SPINMOB_BINARY=binary)
# Now use the header element to determine the binary mode
if 'SPINMOB_BINARY' in self.hkeys:
# Get the binary mode (we'll use this later)
binary = self.pop_header('SPINMOB_BINARY')
# If it's "True", default to float32
if binary in ['True', True, 1]: binary = 'float32'
# Write the special first key.
f.write('SPINMOB_BINARY' + delimiter + binary + '\n')
# Write the usual header
for k in self.hkeys: f.write(k + delimiter + repr(self.headers[k]) + "\n")
f.write('\n')
# if we're not just supposed to write the header
if not header_only:
# Normal ascii saving mode.
if binary in [None, 'None', False, 'False']:
# write the ckeys
elements = []
for ckey in self.ckeys:
elements.append(str(ckey).replace(delimiter,'_'))
f.write(delimiter.join(elements) + "\n")
# now loop over the data
for n in range(0, len(self[0])):
# loop over each column
elements = []
for m in range(0, len(self.ckeys)):
# write the data if there is any, otherwise, placeholder
if n < len(self[m]):
elements.append(str(self[m][n]))
else:
elements.append('_')
f.write(delimiter.join(elements) + "\n")
# Binary mode
else:
# Announce that we're done with the header. It's binary time
f.write('SPINMOB_BINARY\n')
# Loop over the ckeys
for n in range(len(self.ckeys)):
# Get the binary data string
data_string = _n.array(self[n]).astype(binary).tostring()
# Write the column
# ckey + delimiter + count + \n + datastring + \n
f.write(str(self.ckeys[n]).replace(delimiter,'_')
+ delimiter + str(len(self[n])) + '\n')
f.close()
f = open(temporary_path, 'ab')
f.write(data_string)
f.close()
f = open(temporary_path, 'a')
f.write('\n')
f.close()
# now move it
_shutil.move(temporary_path, path)
return self | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L462-L612 |
save list to file | python | def save(
project: 'projects.Project',
write_list: typing.List[tuple] = None
) -> typing.List[tuple]:
"""
Computes the file write list for the current state of the project if no
write_list was specified in the arguments, and then writes each entry in
that list to disk.
:param project:
The project to be saved
:param write_list:
The file writes list for the project if one already exists, or None
if a new writes list should be computed
:return:
The file write list that was used to save the project to disk
"""
try:
writes = (
to_write_list(project)
if write_list is None
else write_list.copy()
)
except Exception as err:
raise
environ.systems.remove(project.output_directory)
os.makedirs(project.output_directory)
file_io.deploy(writes)
return writes | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/__init__.py#L14-L45 |
save list to file | python | def save(self, filename):
'''save settings to a file. Return True/False on success/failure'''
try:
f = open(filename, mode='w')
except Exception:
return False
for k in self.list():
f.write("%s=%s\n" % (k, self.get(k)))
f.close()
return True | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_settings.py#L175-L184 |
save list to file | python | def save_file(self):
"""Write the file out to disk."""
l = []
walk = self.walker
for edit in walk.lines:
# collect the text already stored in edit widgets
if edit.original_text.expandtabs() == edit.edit_text:
l.append(edit.original_text)
else:
l.append(re_tab(edit.edit_text))
# then the rest
while walk.file is not None:
l.append(walk.read_next_line())
# write back to disk
outfile = open(self.save_name, "w")
l_iter = iter(l)
line = next(l_iter)
prefix = ""
while True:
try:
outfile.write(prefix + line)
prefix = "\n"
line = next(l_iter)
except StopIteration:
if line != "\n":
outfile.write("\n")
break | https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L152-L184 |
save list to file | python | def save(self):
'''Save current property list representation to the original file.'''
with open(self.filename, 'w') as plist_file:
plist_file.write(str(self.soup)) | https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/propertylist.py#L112-L115 |
save list to file | python | def save(self, filename, wildcard='*', verbose=False):
'''save parameters to a file'''
f = open(filename, mode='w')
k = list(self.keys())
k.sort()
count = 0
for p in k:
if p and fnmatch.fnmatch(str(p).upper(), wildcard.upper()):
f.write("%-16.16s %f\n" % (p, self.__getitem__(p)))
count += 1
f.close()
if verbose:
print("Saved %u parameters to %s" % (count, filename)) | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavparm.py#L39-L51 |
save list to file | python | def do_save(self, fp=None):
"""Save to file.
Parameters
----------
fp : `file` or `str`, optional
Output file (default: stdout).
"""
if fp is None:
fp = sys.stdout
data = {
'settings': self.settings,
'nodes': self.nodes,
'backward': self.backward
}
json.dump(data, fp, ensure_ascii=False) | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/storage/json.py#L193-L208 |
save list to file | python | def save(fname, data):
"""Saves a list of arrays or a dict of str->array to file.
Examples of filenames:
- ``/path/to/file``
- ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports)
- ``hdfs://path/to/file`` (if compiled with HDFS supports)
Parameters
----------
fname : str
The filename.
data : NDArray, RowSparseNDArray or CSRNDArray, \
or list of NDArray, RowSparseNDArray or CSRNDArray, \
or dict of str to NDArray, RowSparseNDArray or CSRNDArray
The data to save.
Examples
--------
>>> x = mx.nd.zeros((2,3))
>>> y = mx.nd.ones((1,4))
>>> mx.nd.save('my_list', [x,y])
>>> mx.nd.save('my_dict', {'x':x, 'y':y})
>>> mx.nd.load('my_list')
[<NDArray 2x3 @cpu(0)>, <NDArray 1x4 @cpu(0)>]
>>> mx.nd.load('my_dict')
{'y': <NDArray 1x4 @cpu(0)>, 'x': <NDArray 2x3 @cpu(0)>}
"""
if isinstance(data, NDArray):
data = [data]
handles = c_array(NDArrayHandle, [])
if isinstance(data, dict):
str_keys = data.keys()
nd_vals = data.values()
if any(not isinstance(k, string_types) for k in str_keys) or \
any(not isinstance(v, NDArray) for v in nd_vals):
raise TypeError('save only accept dict str->NDArray or list of NDArray')
keys = c_str_array(str_keys)
handles = c_handle_array(nd_vals)
elif isinstance(data, list):
if any(not isinstance(v, NDArray) for v in data):
raise TypeError('save only accept dict str->NDArray or list of NDArray')
keys = None
handles = c_handle_array(data)
else:
raise ValueError("data needs to either be a NDArray, dict of str, NDArray pairs "
"or a list of NDarrays.")
check_call(_LIB.MXNDArraySave(c_str(fname),
mx_uint(len(handles)),
handles,
keys)) | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/utils.py#L222-L273 |
save list to file | python | def save(self, filething=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
fileobj = filething.fileobj
data = _APEv2Data(fileobj)
if data.is_at_start:
delete_bytes(fileobj, data.end - data.start, data.start)
elif data.start is not None:
fileobj.seek(data.start)
# Delete an ID3v1 tag if present, too.
fileobj.truncate()
fileobj.seek(0, 2)
tags = []
for key, value in self.items():
# Packed format for an item:
# 4B: Value length
# 4B: Value type
# Key name
# 1B: Null
# Key value
value_data = value._write()
if not isinstance(key, bytes):
key = key.encode("utf-8")
tag_data = bytearray()
tag_data += struct.pack("<2I", len(value_data), value.kind << 1)
tag_data += key + b"\0" + value_data
tags.append(bytes(tag_data))
# "APE tags items should be sorted ascending by size... This is
# not a MUST, but STRONGLY recommended. Actually the items should
# be sorted by importance/byte, but this is not feasible."
tags.sort(key=lambda tag: (len(tag), tag))
num_tags = len(tags)
tags = b"".join(tags)
header = bytearray(b"APETAGEX")
# version, tag size, item count, flags
header += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER | IS_HEADER)
header += b"\0" * 8
fileobj.write(header)
fileobj.write(tags)
footer = bytearray(b"APETAGEX")
footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER)
footer += b"\0" * 8
fileobj.write(footer) | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/apev2.py#L427-L485 |
save list to file | python | def savetofile(self, filelike, sortkey = True):
"""
Save configurations to a file-like object which supports `writelines`
"""
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L281-L285 |
save list to file | python | def save(self, file_tag='2016', add_header='N'):
"""
save table to folder in appropriate files
NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE
"""
fname = self.get_filename(file_tag)
with open(fname, 'a') as f:
if add_header == 'Y':
f.write(self.format_hdr())
for e in self.table:
f.write(e.format_csv()) | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/core_data.py#L320-L331 |
save list to file | python | def saveFiles(fileName1, fileName2, songs, artist, album, trackNum):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1), tags={'artist': artist, 'album': album, 'track': trackNum})
songs[1].export(fileName2, format=detectFormat(fileName2), tags={'artist': artist, 'album': album, 'track': str(int(trackNum) + 1)}) | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L57-L60 |
save list to file | python | def save(self, filename=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
filename = filename or self.filename
try:
fileobj = open(filename, "r+b")
except IOError:
fileobj = open(filename, "w+b")
data = _APEv2Data(fileobj)
if data.is_at_start:
delete_bytes(fileobj, data.end - data.start, data.start)
elif data.start is not None:
fileobj.seek(data.start)
# Delete an ID3v1 tag if present, too.
fileobj.truncate()
fileobj.seek(0, 2)
# "APE tags items should be sorted ascending by size... This is
# not a MUST, but STRONGLY recommended. Actually the items should
# be sorted by importance/byte, but this is not feasible."
tags = sorted((v._internal(k) for k, v in self.items()), key=len)
num_tags = len(tags)
tags = b"".join(tags)
header = bytearray(b"APETAGEX")
# version, tag size, item count, flags
header += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER | IS_HEADER)
header += b"\0" * 8
fileobj.write(header)
fileobj.write(tags)
footer = bytearray(b"APETAGEX")
footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER)
footer += b"\0" * 8
fileobj.write(footer)
fileobj.close() | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/apev2.py#L386-L432 |
save list to file | python | def file_save(self, name, filename=None, folder="", keep_ext=True) -> bool:
""" Easy save of a file """
if name in self.files:
file_object = self.files[name]
clean_filename = secure_filename(file_object.filename)
if filename is not None and keep_ext:
clean_filename = filename + ".%s" % \
(clean_filename.rsplit('.', 1)[1].lower())
elif filename is not None and not keep_ext:
clean_filename = filename
file_object.save(os.path.join(
current_app.config['UPLOADS']['FOLDER'],
folder, clean_filename))
return None | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/form_data.py#L48-L61 |
save list to file | python | def save(self, filething=None, v1=1, v2_version=4, v23_sep='/',
padding=None):
"""save(filething=None, v1=1, v2_version=4, v23_sep='/', padding=None)
Save changes to a file.
Args:
filething (filething):
Filename to save the tag to. If no filename is given,
the one most recently loaded is used.
v1 (ID3v1SaveOptions):
if 0, ID3v1 tags will be removed.
if 1, ID3v1 tags will be updated but not added.
if 2, ID3v1 tags will be created and/or updated
v2 (int):
version of ID3v2 tags (3 or 4).
v23_sep (text):
the separator used to join multiple text values
if v2_version == 3. Defaults to '/' but if it's None
will be the ID3v2v2.4 null separator.
padding (:obj:`mutagen.PaddingFunction`)
Raises:
mutagen.MutagenError
By default Mutagen saves ID3v2.4 tags. If you want to save ID3v2.3
tags, you must call method update_to_v23 before saving the file.
The lack of a way to update only an ID3v1 tag is intentional.
"""
f = filething.fileobj
try:
header = ID3Header(filething.fileobj)
except ID3NoHeaderError:
old_size = 0
else:
old_size = header.size
data = self._prepare_data(
f, 0, old_size, v2_version, v23_sep, padding)
new_size = len(data)
if (old_size < new_size):
insert_bytes(f, new_size - old_size, old_size)
elif (old_size > new_size):
delete_bytes(f, old_size - new_size, new_size)
f.seek(0)
f.write(data)
self.__save_v1(f, v1) | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_file.py#L223-L274 |
save list to file | python | def save(self):
"""
Save the state to a file.
"""
with open(self.path, 'w') as f:
f.write(yaml.dump(dict(self.d))) | https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/state.py#L54-L59 |
save list to file | python | def save_to(self, file):
"""Save data to file.
Will copy by either writing out the data or using
:func:`shutil.copyfileobj`.
:param file: A file-like object (with a ``write`` method) or a
filename."""
dest = file
if hasattr(dest, 'write'):
# writing to a file-like
# only works when no unicode conversion is done
if self.file is not None and\
getattr(self.file, 'encoding', None) is None:
copyfileobj(self.file, dest)
elif self.filename is not None:
with open(self.filename, 'rb') as inp:
copyfileobj(inp, dest)
else:
dest.write(self.__bytes__())
else:
# we do not use filesystem io to make sure we have the same
# permissions all around
# copyfileobj() should be efficient enough
# destination is a filename
with open(dest, 'wb') as out:
return self.save_to(out) | https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L203-L231 |
save list to file | python | def _save(file, data, mode='w+'):
"""
Write all data to created file. Also overwrite previous file.
"""
with open(file, mode) as fh:
fh.write(data) | https://github.com/xgvargas/js-css-min-django/blob/29300bef0d72b523c41deb72ef19bb1d24a619bb/jscssmin.py#L32-L37 |
save list to file | python | def save_varlist(filename, varnames, varlist):
"""
Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'
@param filename: string
@param varnames: list of strings
Names of the variables
@param varlist: list of objects
The objects to be saved
"""
variables = {}
for i, vn in enumerate(varnames):
variables[vn] = varlist[i]
ExportData.save_variables(filename, variables) | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/storage.py#L158-L174 |
save list to file | python | def _save_file(self, data):
"""Attempt to atomically save file by saving and then moving into position
The goal is to make it difficult for a crash to corrupt our data file since
the move operation can be made atomic if needed on mission critical filesystems.
"""
if platform.system() == 'Windows':
with open(self.file, "w") as outfile:
json.dump(data, outfile)
else:
newpath = self.file + '.new'
with open(newpath, "w") as outfile:
json.dump(data, outfile)
os.rename(
os.path.realpath(newpath),
os.path.realpath(self.file)
) | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/kvstore_json.py#L60-L79 |
save list to file | python | def saveFiles(fileName1, fileName2, songs):
"""Save songs to files"""
songs[0].export(fileName1, format=detectFormat(fileName1))
songs[1].export(fileName2, format=detectFormat(fileName2)) | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L52-L55 |
save list to file | python | def OnMacroListSave(self, event):
"""Macro list save event handler"""
# Get filepath from user
wildcards = get_filetypes2wildcards(["py", "all"]).values()
wildcard = "|".join(wildcards)
message = _("Choose macro file.")
style = wx.SAVE
filepath, filterindex = \
self.interfaces.get_filepath_findex_from_user(wildcard, message,
style)
if filepath is None:
return
# Save macros to file
macros = self.main_window.grid.code_array.macros
self.main_window.actions.save_macros(filepath, macros)
event.Skip() | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L1489-L1513 |
save list to file | python | def save(self, filename, addnormalised=False):
"""Save a frequency list to file, can be loaded later using the load method"""
f = io.open(filename,'w',encoding='utf-8')
for line in self.output("\t", addnormalised):
f.write(line + '\n')
f.close() | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L64-L69 |
save list to file | python | def save(self):
"""
Deletes the selected files from storage
"""
storage = get_media_storage()
for storage_name in self.cleaned_data['selected_files']:
full_path = storage.path(storage_name)
try:
storage.delete(storage_name)
self.success_files.append(full_path)
except OSError:
self.error_files.append(full_path) | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/forms.py#L204-L215 |
save list to file | python | def save(self, data, fname, header=None):
"""
Save data on fname.
:param data: numpy array or list of lists
:param fname: path name
:param header: header to use
"""
write_csv(fname, data, self.sep, self.fmt, header)
self.fnames.add(getattr(fname, 'name', fname)) | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L265-L274 |
save list to file | python | def _save_vocab_file(vocab_file, subtoken_list):
"""Save subtokens to file."""
with tf.gfile.Open(vocab_file, mode="w") as f:
for subtoken in subtoken_list:
f.write("'%s'\n" % _unicode_to_native(subtoken)) | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L185-L189 |
save list to file | python | def save_file_list(key, *files_refs):
"""Convert the given parameters to a special JSON object.
Each parameter is a file-refs specification of the form:
<file-path>:<reference1>,<reference2>, ...,
where the colon ':' and the list of references are optional.
JSON object is of the form:
{ key: {"file": file_path}}, or
{ key: {"file": file_path, "refs": [refs[0], refs[1], ... ]}}
"""
file_list = []
for file_refs in files_refs:
if ':' in file_refs:
try:
file_name, refs = file_refs.split(':')
except ValueError as e:
return error("Only one colon ':' allowed in file-refs specification.")
else:
file_name, refs = file_refs, None
if not os.path.isfile(file_name):
return error(
"Output '{}' set to a missing file: '{}'.".format(key, file_name)
)
file_obj = {'file': file_name}
if refs:
refs = [ref_path.strip() for ref_path in refs.split(',')]
missing_refs = [
ref for ref in refs if not (os.path.isfile(ref) or os.path.isdir(ref))
]
if len(missing_refs) > 0:
return error(
"Output '{}' set to missing references: '{}'.".format(
key, ', '.join(missing_refs)
)
)
file_obj['refs'] = refs
file_list.append(file_obj)
return json.dumps({key: file_list}) | https://github.com/genialis/resolwe-runtime-utils/blob/5657d7cf981972a5259b9b475eae220479401001/resolwe_runtime_utils.py#L101-L143 |
save list to file | python | def save(self, name, file):
"""
Saves new content to the file specified by name. The content should be
a proper File object or any python file-like object, ready to be read
from the beginning.
"""
# Get the proper name for the file, as it will actually be saved.
if name is None:
name = file.name
if not hasattr(file, 'chunks'):
file = File(file, name=name)
name = self.get_available_name(name)
name = self._save(name, file)
# Store filenames with forward slashes, even on Windows
return name.replace('\\', '/') | https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/storage.py#L50-L67 |
save list to file | python | def save_to_file(destination_filename, append=False):
"""
Save the output value to file.
"""
def decorator_fn(f):
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
makedirs(os.path.dirname(destination_filename))
mode = "a" if append else "w"
with open(destination_filename, mode) as text_file:
text_file.write(res)
return res
return wrapper_fn
return decorator_fn | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L48-L67 |
save list to file | python | def save(self):
"""Write changed .pth file back to disk"""
if not self.dirty:
return
data = '\n'.join(map(self.make_relative, self.paths))
if data:
log.debug("Saving %s", self.filename)
data = (
"import sys; sys.__plen = len(sys.path)\n"
"%s\n"
"import sys; new=sys.path[sys.__plen:];"
" del sys.path[sys.__plen:];"
" p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;"
" sys.__egginsert = p+len(new)\n"
) % data
if os.path.islink(self.filename):
os.unlink(self.filename)
f = open(self.filename, 'wt')
f.write(data)
f.close()
elif os.path.exists(self.filename):
log.debug("Deleting empty %s", self.filename)
os.unlink(self.filename)
self.dirty = False | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L1528-L1555 |
save list to file | python | def save_all(self):
"""Save all opened files.
Iterate through self.data and call save() on any modified files.
"""
for index in range(self.get_stack_count()):
if self.data[index].editor.document().isModified():
self.save(index) | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L1897-L1904 |
save list to file | python | def saveToFile(self):
"""
Save the current text to file
"""
filename = self.codeEditor.dialog.getSaveFileName()
if filename and filename != '.':
with open(filename, 'w') as f:
f.write(self.toPlainText())
print('saved script under %s' % filename) | https://github.com/radjkarl/fancyWidgets/blob/ffe0d5747c5296c78575f0e0909af915a4a5698f/fancywidgets/pyQtBased/CodeEditor.py#L306-L314 |
save list to file | python | def save(self, *args, **kwargs):
"""save(filething=None, padding=None)"""
super(MP4, self).save(*args, **kwargs) | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/__init__.py#L1086-L1089 |
save list to file | python | def save_to_file(self, fname):
"""
saves a characters data to file
"""
with open(fname, 'w') as f:
f.write(str(self)) | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L236-L241 |
save list to file | python | def save(self, mode='all'):
"""Saves to the file specified by :attr:`~SR850.filename`.
:param mode: Defines what to save.
======= ================================================
Value Description
======= ================================================
'all' Saves the active display's data trace, the trace
definition and the instrument state.
'data' Saves the active display's data trace.
'state' Saves the instrument state.
======= ================================================
"""
if mode == 'all':
self._write('SDAT')
elif mode == 'data':
self._write('SASC')
elif mode=='state':
self._write('SSET')
else:
raise ValueError('Invalid save mode.') | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/srs/sr850.py#L730-L752 |
save list to file | python | def save(self, filename):
"""
Save document to a file.
Parameters
----------
filename : str
The output string filename
"""
self.doc.save(os.path.expanduser(filename)) | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/reporter.py#L159-L169 |
save list to file | python | def save_to_file(self, text, filename, name=None):
'''
Adds an utterance to speak to the event queue.
@param text: Text to sepak
@type text: unicode
@param filename: the name of file to save.
@param name: Name to associate with this utterance. Included in
notifications about this utterance.
@type name: str
'''
self.proxy.save_to_file(text, filename, name) | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L108-L119 |
save list to file | python | def save_file(self, filename, text):
"""Save the given text under the given control filename and the
current path."""
if not filename.endswith('.py'):
filename += '.py'
path = os.path.join(self.currentpath, filename)
with open(path, 'w', encoding="utf-8") as file_:
file_.write(text) | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/filetools.py#L873-L880 |
save list to file | python | def saveAs(self, event=None):
""" Save the parameter settings to a user-specified file. Any
changes here must be coordinated with the corresponding tpar save_as
function. """
self.debug('Clicked Save as...')
# On Linux Pers..Dlg causes the cwd to change, so get a copy of current
curdir = os.getcwd()
# The user wishes to save to a different name
writeProtChoice = self._writeProtectOnSaveAs
if capable.OF_TKFD_IN_EPAR:
# Prompt using native looking dialog
fname = asksaveasfilename(parent=self.top,
title='Save Parameter File As',
defaultextension=self._defSaveAsExt,
initialdir=os.path.dirname(self._getSaveAsFilter()))
else:
# Prompt. (could use tkinter's FileDialog, but this one is prettier)
# initWProtState is only used in the 1st call of a session
from . import filedlg
fd = filedlg.PersistSaveFileDialog(self.top,
"Save Parameter File As", self._getSaveAsFilter(),
initWProtState=writeProtChoice)
if fd.Show() != 1:
fd.DialogCleanup()
os.chdir(curdir) # in case file dlg moved us
return
fname = fd.GetFileName()
writeProtChoice = fd.GetWriteProtectChoice()
fd.DialogCleanup()
if not fname: return # canceled
# First check the child parameters, aborting save if
# invalid entries were encountered
if self.checkSetSaveChildren():
os.chdir(curdir) # in case file dlg moved us
return
# Run any subclass-specific steps right before the save
self._saveAsPreSave_Hook(fname)
# Verify all the entries (without save), keeping track of the invalid
# entries which have been reset to their original input values
self.badEntriesList = self.checkSetSaveEntries(doSave=False)
# If there were invalid entries, prepare the message dialog
if self.badEntriesList:
ansOKCANCEL = self.processBadEntries(self.badEntriesList,
self.taskName)
if not ansOKCANCEL:
os.chdir(curdir) # in case file dlg moved us
return
# If there were no invalid entries or the user says OK, finally
# save to their stated file. Since we have already processed the
# bad entries, there should be none returned.
mstr = "TASKMETA: task="+self.taskName+" package="+self.pkgName
if self.checkSetSaveEntries(doSave=True, filename=fname, comment=mstr,
set_ro=writeProtChoice,
overwriteRO=True):
os.chdir(curdir) # in case file dlg moved us
raise Exception("Unexpected bad entries for: "+self.taskName)
# Run any subclass-specific steps right after the save
self._saveAsPostSave_Hook(fname)
os.chdir(curdir) | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/editpar.py#L1122-L1190 |
save list to file | python | def save(self, filename):
"""
saves the instance of the script to a file using pickle
Args:
filename: target filename
"""
if filename is None:
filename = self.filename('.b26s')
# if len(filename.split('\\\\?\\')) == 1:
# filename = '\\\\?\\' + filename
with open(filename, 'w') as outfile:
outfile.write(pickle.dumps(self.__dict__)) | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L746-L759 |
save list to file | python | def batch_save(self, *documents):
"""
Inserts or updates every document specified in documents.
:param documents: Array of documents to save as dictionaries
:type documents: ``array`` of ``dict``
:return: Results of update operation as overall stats
:rtype: ``dict``
"""
if len(documents) < 1:
raise Exception('Must have at least one document.')
data = json.dumps(documents)
return json.loads(self._post('batch_save', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3715-L3730 |
save list to file | python | def save_to_file(filename, content):
"""
Save content to file. Used by node initial contact but
can be used anywhere.
:param str filename: name of file to save to
:param str content: content to save
:return: None
:raises IOError: permissions issue saving, invalid directory, etc
"""
import os.path
path = os.path.abspath(filename)
with open(path, "w") as text_file:
text_file.write("{}".format(content)) | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L55-L68 |
save list to file | python | def save_as(self, index=None):
"""Save file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
Gets the new file name from select_savename(). If no name is chosen,
then the save_as() aborts. Otherwise, the current stack is checked
to see if the selected name already exists and, if so, then the tab
with that name is closed.
The current stack (self.data) and current tabs are updated with the
new name and other file info. The text is written with the new
name using save() and the name change is propagated to the other stacks
via the file_renamed_in_data signal.
"""
if index is None:
# Save the currently edited file
index = self.get_stack_index()
finfo = self.data[index]
# The next line is necessary to avoid checking if the file exists
# While running __check_file_status
# See issues 3678 and 3026
finfo.newly_created = True
original_filename = finfo.filename
filename = self.select_savename(original_filename)
if filename:
ao_index = self.has_filename(filename)
# Note: ao_index == index --> saving an untitled file
if ao_index is not None and ao_index != index:
if not self.close_file(ao_index):
return
if ao_index < index:
index -= 1
new_index = self.rename_in_data(original_filename,
new_filename=filename)
# We pass self object ID as a QString, because otherwise it would
# depend on the platform: long for 64bit, int for 32bit. Replacing
# by long all the time is not working on some 32bit platforms
# (see Issue 1094, Issue 1098)
self.file_renamed_in_data.emit(str(id(self)),
original_filename, filename)
ok = self.save(index=new_index, force=True)
self.refresh(new_index)
self.set_stack_index(new_index)
return ok
else:
return False | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L1790-L1844 |
save list to file | python | def save(self, filething=None, padding=None):
"""save(filething=None, padding=None)
Save a tag to a file.
If no filename is given, the one most recently loaded is used.
Args:
filething (filething)
padding (:obj:`mutagen.PaddingFunction`)
Raises:
mutagen.MutagenError
"""
try:
self.tags._inject(filething.fileobj, padding)
except (IOError, error) as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found") | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/ogg.py#L570-L589 |
save list to file | python | def save(self, filename):
"""Save the configuration to a file"""
filename = pathlib.Path(filename)
out = []
keys = sorted(list(self.keys()))
for key in keys:
out.append("[{}]".format(key))
section = self[key]
ikeys = list(section.keys())
ikeys.sort()
for ikey in ikeys:
var, val = keyval_typ2str(ikey, section[ikey])
out.append("{} = {}".format(var, val))
out.append("")
with filename.open("w") as f:
for i in range(len(out)):
# win-like line endings
out[i] = out[i]+"\n"
f.writelines(out) | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/config.py#L160-L179 |
save list to file | python | def save_list(self, list_name, emails):
"""
Upload a list. The list import job is queued and will happen shortly after the API request.
http://docs.sailthru.com/api/list
@param list: list name
@param emails: List of email values or comma separated string
"""
data = {'list': list_name,
'emails': ','.join(emails) if isinstance(emails, list) else emails}
return self.api_post('list', data) | https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L356-L365 |
save list to file | python | def save(
self,
copypath=None):
"""*save the content of the document back to the file*
**Key Arguments:**
- ``copypath`` -- the path to a new file if you want to make a copy of the document instead of saving it to the original filepath. Default *None*
**Usage:**
To save the document to file run:
.. code-block:: python
doc.save()
Or to copy the content to another file run the save method with a new filepath as an argument:
.. code-block:: python
doc.save("/path/to/saturday-tasks-copy.taskpaper")
"""
self.refresh
if copypath:
self.filepath = copypath
content = self.content
import codecs
# SET ENCODE ERROR RETURN VALUE
writeFile = codecs.open(self.filepath, encoding='utf-8', mode='w')
writeFile.write(content)
writeFile.close()
return None | https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L1327-L1362 |
save list to file | python | def save(self, name, content):
"""
Saves new content to the file specified by name. The content should be a
proper File object, ready to be read from the beginning.
"""
# Get the proper name for the file, as it will actually be saved.
if name is None:
name = content.name
name = self.get_available_name(name)
name = self._save(name, content)
# Store filenames with forward slashes, even on Windows
return name.replace("\\", "/") | https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/core.py#L55-L68 |
save list to file | python | def _save_file(self, filename, contents):
"""write the html file contents to disk"""
with open(filename, 'w') as f:
f.write(contents) | https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/generator.py#L49-L52 |
save list to file | python | def save(file_name, content):
"""Save content to a file"""
with open(file_name, "w", encoding="utf-8") as output_file:
output_file.write(content)
return output_file.name | https://github.com/vividvilla/csvtotable/blob/d894dca1fcc1071c9a52260a9194f8cc3b327905/csvtotable/convert.py#L71-L75 |
save list to file | python | def save_to_file(self, fp, sep='\n'):
"""
Read all messages from the queue and persist them to file-like object.
Messages are written to the file and the 'sep' string is written
in between messages. Messages are deleted from the queue after
being written to the file.
Returns the number of messages saved.
"""
n = 0
m = self.read()
while m:
n += 1
fp.write(m.get_body())
if sep:
fp.write(sep)
self.delete_message(m)
m = self.read()
return n | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sqs/queue.py#L320-L337 |
save list to file | python | def file_to_list(in_file):
''' Reads file into list '''
lines = []
for line in in_file:
# Strip new line
line = line.strip('\n')
# Ignore empty lines
if line != '':
# Ignore comments
if line[0] != '#':
lines.append(line)
return lines | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L39-L52 |
save list to file | python | def tplot_save(names, filename=None):
"""
This function will save tplot variables into a single file by using the python "pickle" function.
This file can then be "restored" using tplot_restore. This is useful if you want to end the pytplot session,
but save all of your data/options. All variables and plot options can be read back into tplot with the
"tplot_restore" command.
Parameters:
names : str/list
A string or a list of strings of the tplot variables you would like saved.
filename : str, optional
The filename where you want to save the file.
Returns:
None
Examples:
>>> # Save a single tplot variable
>>> import pytplot
>>> x_data = [1,2,3,4,5]
>>> y_data = [1,2,3,4,5]
>>> pytplot.store_data("Variable1", data={'x':x_data, 'y':y_data})
>>> pytplot.ylim('Variable1', 2, 4)
>>> pytplot.save('Variable1', filename='C:/temp/variable1.pytplot')
"""
if isinstance(names,int):
names = list(data_quants.keys())[names-1]
if not isinstance(names, list):
names = [names]
#Check that we have all available data
for name in names:
if isinstance(data_quants[name].data, list):
for data_name in data_quants[name].data:
if data_name not in names:
names.append(data_name)
#Pickle it up
to_pickle =[]
for name in names:
if name not in data_quants.keys():
print("That name is currently not in pytplot")
return
to_pickle.append(data_quants[name])
num_quants = len(to_pickle)
to_pickle = [num_quants] + to_pickle
temp_tplot_opt_glob = tplot_opt_glob
to_pickle.append(temp_tplot_opt_glob)
if filename==None:
filename='var_'+'-'.join(names)+'.pytplot'
pickle.dump(to_pickle, open(filename, "wb"))
return | https://github.com/MAVENSDC/PyTplot/blob/d76cdb95363a4bd4fea6bca7960f8523efa7fa83/pytplot/tplot_save.py#L9-L65 |
save list to file | python | def save(self, to_save, manipulate=True, check_keys=True, **kwargs):
"""Save a document in this collection.
**DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations.
"""
warnings.warn("save is deprecated. Use insert_one or replace_one "
"instead", DeprecationWarning, stacklevel=2)
common.validate_is_document_type("to_save", to_save)
write_concern = None
collation = validate_collation_or_none(kwargs.pop('collation', None))
if kwargs:
write_concern = WriteConcern(**kwargs)
with self._socket_for_writes() as sock_info:
if not (isinstance(to_save, RawBSONDocument) or "_id" in to_save):
return self._insert(sock_info, to_save, True,
check_keys, manipulate, write_concern)
else:
self._update(sock_info, {"_id": to_save["_id"]}, to_save, True,
check_keys, False, manipulate, write_concern,
collation=collation)
return to_save.get("_id") | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py#L2456-L2482 |
save list to file | python | def save_copy_as(self, index=None):
"""Save copy of file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
Gets the new file name from select_savename(). If no name is chosen,
then the save_copy_as() aborts. Otherwise, the current stack is
checked to see if the selected name already exists and, if so, then the
tab with that name is closed.
Unlike save_as(), this calls write() directly instead of using save().
The current file and tab aren't changed at all. The copied file is
opened in a new tab.
"""
if index is None:
# Save the currently edited file
index = self.get_stack_index()
finfo = self.data[index]
original_filename = finfo.filename
filename = self.select_savename(original_filename)
if filename:
ao_index = self.has_filename(filename)
# Note: ao_index == index --> saving an untitled file
if ao_index is not None and ao_index != index:
if not self.close_file(ao_index):
return
if ao_index < index:
index -= 1
try:
self._write_to_file(finfo, filename)
# open created copy file
self.plugin_load.emit(filename)
return True
except EnvironmentError as error:
self.msgbox = QMessageBox(
QMessageBox.Critical,
_("Save Error"),
_("<b>Unable to save file '%s'</b>"
"<br><br>Error message:<br>%s"
) % (osp.basename(finfo.filename),
str(error)),
parent=self)
self.msgbox.exec_()
else:
return False | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L1846-L1895 |
save list to file | python | def save_files(self, nodes):
"""
Saves user defined files using give nodes.
:param nodes: Nodes.
:type nodes: list
:return: Method success.
:rtype: bool
"""
metrics = {"Opened": 0, "Cached": 0}
for node in nodes:
file = node.file
if self.__container.get_editor(file):
if self.__container.save_file(file):
metrics["Opened"] += 1
self.__uncache(file)
else:
cache_data = self.__files_cache.get_content(file)
if cache_data is None:
LOGGER.warning(
"!> {0} | '{1}' file doesn't exists in files cache!".format(self.__class__.__name__, file))
continue
if cache_data.document:
file_handle = File(file)
file_handle.content = [cache_data.document.toPlainText().toUtf8()]
if file_handle.write():
metrics["Cached"] += 1
self.__uncache(file)
else:
LOGGER.warning(
"!> {0} | '{1}' file document doesn't exists in files cache!".format(self.__class__.__name__,
file))
self.__container.engine.notifications_manager.notify(
"{0} | '{1}' opened file(s) and '{2}' cached file(s) saved!".format(self.__class__.__name__,
metrics["Opened"],
metrics["Cached"])) | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/search_in_files.py#L1405-L1443 |
save list to file | python | def save(self, fname):
"""Saves symbol to a file.
You can also use pickle to do the job if you only work on python.
The advantage of `load`/`save` functions is that the file contents are language agnostic.
This means the model saved by one language binding can be loaded by a different
language binding of `MXNet`.
You also get the benefit of being able to directly load/save from cloud storage(S3, HDFS).
Parameters
----------
fname : str
The name of the file.
- "s3://my-bucket/path/my-s3-symbol"
- "hdfs://my-bucket/path/my-hdfs-symbol"
- "/path-to/my-local-symbol"
See Also
--------
symbol.load : Used to load symbol from file.
"""
if not isinstance(fname, string_types):
raise TypeError('fname need to be string')
check_call(_LIB.MXSymbolSaveToFile(self.handle, c_str(fname))) | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/symbol.py#L1278-L1302 |
save list to file | python | def save(self, event):
"""Saves a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be saved
"""
filepath = event.attr["filepath"]
try:
filetype = event.attr["filetype"]
except KeyError:
filetype = "pys"
# If saving is already in progress abort
if self.saving:
return
# Use tmpfile to make sure that old save file does not get lost
# on abort save
__, tmpfilepath = tempfile.mkstemp()
if filetype == "xls":
self._set_save_states()
self._save_xls(tmpfilepath)
self._move_tmp_file(tmpfilepath, filepath)
self._release_save_states()
elif filetype == "pys" or filetype == "all":
self._set_save_states()
if self._save_pys(tmpfilepath):
# Writing was successful
self._move_tmp_file(tmpfilepath, filepath)
self._save_sign(filepath)
self._release_save_states()
elif filetype == "pysu":
self._set_save_states()
if self._save_pysu(tmpfilepath):
# Writing was successful
self._move_tmp_file(tmpfilepath, filepath)
self._save_sign(filepath)
self._release_save_states()
else:
os.remove(tmpfilepath)
msg = "Filetype {filetype} unknown.".format(filetype=filetype)
raise ValueError(msg)
try:
os.remove(tmpfilepath)
except OSError:
pass | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_actions.py#L606-L662 |
save list to file | python | def file_list(self):
"""list files on the device"""
log.info('Listing files')
res = self.__exchange(LIST_FILES)
res = res.split('\r\n')
# skip first and last lines
res = res[1:-1]
files = []
for line in res:
files.append(line.split('\t'))
return files | https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L408-L418 |
save list to file | python | def save(self, outpath):
"""Save this command file as an ascii file.
Agrs:
outpath (str): The output path to save.
"""
with open(outpath, "w") as outfile:
outfile.write(self.dump()) | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L49-L57 |
save list to file | python | def save(self):
""" Saves the settings contents """
content = self.dumps()
fileutils.save_text_to_file(content, self.file_path) | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L53-L56 |
save list to file | python | def save(self, p_todolist):
"""
Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is closed afterwards.
"""
self._trim()
current_hash = hash_todolist(p_todolist)
list_todo = (self.todolist.print_todos()+'\n').splitlines(True)
try:
list_archive = (self.archive.print_todos()+'\n').splitlines(True)
except AttributeError:
list_archive = []
self.backup_dict[self.timestamp] = (list_todo, list_archive, self.label)
index = self._get_index()
index.insert(0, (self.timestamp, current_hash))
self._save_index(index)
self._write()
self.close() | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L96-L119 |
save list to file | python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | https://github.com/tallero/trovotutto/blob/7afcfacf2bb3b642654153630c1ab7447ab10fae/trovotutto/__init__.py#L45-L54 |
save list to file | python | def save(self, filename, callback=_noop_callback):
"""Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
"""
with open(filename, 'wb') as fp:
self._save(fp, callback) | https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/savfile.py#L312-L321 |
save list to file | python | def _save(self):
"""
save the cache index, in case it was modified.
Saves the index table and the file name repository in the file
`index.dat`
"""
if self.__modified_flag:
self.__filename_rep.update_id_counter()
indexfilename = os.path.join(self.__dir, "index.dat")
self._write_file(
indexfilename,
(self.__index,
self.__filename_rep))
self.__modified_flag = False | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L245-L261 |
save list to file | python | def save(self, revision=True, *args, **kwargs):
"""
Handles the saving/updating of a Publishable instance.
Arguments:
revision - if True, a new version of this Publishable will be created.
"""
if revision:
# If this is a revision, set it to be the head of the list and increment the revision id
self.head = True
self.revision_id += 1
previous_revision = self.get_previous_revision()
if not self.is_parent():
# If this is a revision, delete the old head of the list.
type(self).objects \
.filter(parent=self.parent, head=True) \
.update(head=None)
# Clear the instance id to force Django to save a new instance.
# Both fields (pk, id) required for this to work -- something to do with model inheritance
self.pk = None
self.id = None
# New version is unpublished by default
self.is_published = None
# Set created_at to current time, but only for first version
if not self.created_at:
self.created_at = timezone.now()
self.updated_at = timezone.now()
if revision:
self.updated_at = timezone.now()
super(Publishable, self).save(*args, **kwargs)
# Update the parent foreign key
if not self.parent:
self.parent = self
super(Publishable, self).save(update_fields=['parent'])
if revision:
# Set latest version for all articles
type(self).objects \
.filter(parent=self.parent) \
.update(latest_version=self.revision_id)
self.latest_version = self.revision_id
return self | https://github.com/ubyssey/dispatch/blob/8da6084fe61726f20e9cf675190480cfc45ee764/dispatch/modules/content/models.py#L170-L222 |
save list to file | python | def save(self):
"""Write the store dict to a file specified by store_file_path"""
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L253-L257 |
save list to file | python | def saveParList(self, *args, **kw):
"""Write parameter data to filename (string or filehandle)"""
if 'filename' in kw:
filename = kw['filename']
if not filename:
filename = self.getFilename()
if not filename:
raise ValueError("No filename specified to save parameters")
if hasattr(filename,'write'):
fh = filename
absFileName = os.path.abspath(fh.name)
else:
absFileName = os.path.expanduser(filename)
absDir = os.path.dirname(absFileName)
if len(absDir) and not os.path.isdir(absDir): os.makedirs(absDir)
fh = open(absFileName,'w')
numpars = len(self.__paramList)
if self._forUseWithEpar: numpars -= 1
if not self.final_comment: self.final_comment = [''] # force \n at EOF
# Empty the ConfigObj version of section.defaults since that is based
# on an assumption incorrect for us, and override with our own list.
# THIS IS A BIT OF MONKEY-PATCHING! WATCH FUTURE VERSION CHANGES!
# See Trac ticket #762.
while len(self.defaults):
self.defaults.pop(-1) # empty it, keeping ref
for key in self._neverWrite:
self.defaults.append(key)
# Note also that we are only overwriting the top/main section's
# "defaults" list, but EVERY [sub-]section has such an attribute...
# Now write to file, delegating work to ConfigObj (note that ConfigObj
# write() skips any items listed by name in the self.defaults list)
self.write(fh)
fh.close()
retval = str(numpars) + " parameters written to " + absFileName
self.filename = absFileName # reset our own ConfigObj filename attr
self.debug('Keys not written: '+str(self.defaults))
return retval | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/cfgpars.py#L752-L790 |
save list to file | python | def save(self, fp=None):
"""Save to file.
Parameters
----------
fp : `file`, optional
Output file.
"""
self.storage.settings['markov'] = self.get_settings_json()
self.storage.save(fp) | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/base.py#L115-L124 |
save list to file | python | def save(self, path):
"""
Save the file to the specified path
"""
# remember and restore file position
pos = self.tell()
self.seek(0)
with fopen(path, 'wb') as output:
output.truncate(self.length)
for chunk in iter(lambda: self.read(1024), b''):
output.write(chunk)
self.seek(pos) | https://github.com/ValvePython/vpk/blob/cc522fc7febbf53efa5d58fcd1ad2103dae37ac8/vpk/__init__.py#L454-L467 |
save list to file | python | def save(self):
"""Store config back to file."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
with open(self._configfile, 'w') as f:
self._config.write(f) | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/config.py#L80-L88 |
save list to file | python | def save(store, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.
Parameters
----------
store : MutableMapping or string
Store or path to directory in file system or name of zip file.
args : ndarray
NumPy arrays with data to save.
kwargs
NumPy arrays with data to save.
Examples
--------
Save an array to a directory on the file system (uses a :class:`DirectoryStore`)::
>>> import zarr
>>> import numpy as np
>>> arr = np.arange(10000)
>>> zarr.save('data/example.zarr', arr)
>>> zarr.load('data/example.zarr')
array([ 0, 1, 2, ..., 9997, 9998, 9999])
Save an array to a Zip file (uses a :class:`ZipStore`)::
>>> zarr.save('data/example.zip', arr)
>>> zarr.load('data/example.zip')
array([ 0, 1, 2, ..., 9997, 9998, 9999])
Save several arrays to a directory on the file system (uses a
:class:`DirectoryStore` and stores arrays in a group)::
>>> import zarr
>>> import numpy as np
>>> a1 = np.arange(10000)
>>> a2 = np.arange(10000, 0, -1)
>>> zarr.save('data/example.zarr', a1, a2)
>>> loader = zarr.load('data/example.zarr')
>>> loader
<LazyLoader: arr_0, arr_1>
>>> loader['arr_0']
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> loader['arr_1']
array([10000, 9999, 9998, ..., 3, 2, 1])
Save several arrays using named keyword arguments::
>>> zarr.save('data/example.zarr', foo=a1, bar=a2)
>>> loader = zarr.load('data/example.zarr')
>>> loader
<LazyLoader: bar, foo>
>>> loader['foo']
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> loader['bar']
array([10000, 9999, 9998, ..., 3, 2, 1])
Store several arrays in a single zip file (uses a :class:`ZipStore`)::
>>> zarr.save('data/example.zip', foo=a1, bar=a2)
>>> loader = zarr.load('data/example.zip')
>>> loader
<LazyLoader: bar, foo>
>>> loader['foo']
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> loader['bar']
array([10000, 9999, 9998, ..., 3, 2, 1])
See Also
--------
save_array, save_group
"""
if len(args) == 0 and len(kwargs) == 0:
raise ValueError('at least one array must be provided')
if len(args) == 1 and len(kwargs) == 0:
save_array(store, args[0])
else:
save_group(store, *args, **kwargs) | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L222-L299 |
save list to file | python | def save(self, content):
"""
Save any given content to the instance file.
:param content: (str or bytes)
:return: (None)
"""
# backup existing file if needed
if os.path.exists(self.file_path) and not self.assume_yes:
message = "Overwrite existing {}? (y/n) "
if not confirm(message.format(self.filename)):
self.backup()
# write file
self.output("Saving " + self.filename)
with open(self.file_path, "wb") as handler:
if not isinstance(content, bytes):
content = bytes(content, "utf-8")
handler.write(content)
self.yeah("Done!") | https://github.com/cuducos/getgist/blob/c70a0a9353eca43360b82c759d1e1514ec265d3b/getgist/local.py#L23-L41 |
save list to file | python | def save(self, filename):
"""
Saves the data for this settings instance to the given filename.
:param filename | <str>
"""
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
try:
f = open(filename, 'w')
except StandardError:
log.error('Failed to access file: {0}'.format(filename))
return False
try:
f.write(yaml.dump(self._root, default_flow_style=False))
except StandardError:
log.error('Failed to save settings: {0}'.format(filename))
return False
finally:
f.close()
return True | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L434-L458 |
save list to file | python | def save(self, file, contents, name=None, overwrite=False):
"""Save contents into a file. The format name can be specified
explicitly or inferred from the file extension."""
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(name)
if file_format == 'text':
_write_text(file, contents)
elif file_format == 'json':
_write_json(file, contents)
else:
write_function = self._formats[name].get('save', None)
if write_function is None:
raise IOError("The format must declare a file type or "
"load/save functions.")
if op.exists(file) and not overwrite:
print("The file already exists, please use overwrite=True.")
return
write_function(file, contents) | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L183-L201 |
save list to file | python | def save_playlist_file(self, stationFile=''):
""" Save a playlist
Create a txt file and write stations in it.
Then rename it to final target
return 0: All ok
-1: Error writing file
-2: Error renaming file
"""
if self._playlist_format_changed():
self.dirty_playlist = True
self.new_format = not self.new_format
if stationFile:
st_file = stationFile
else:
st_file = self.stations_file
if not self.dirty_playlist:
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Playlist not modified...')
return 0
st_new_file = st_file.replace('.csv', '.txt')
tmp_stations = self.stations[:]
tmp_stations.reverse()
if self.new_format:
tmp_stations.append([ '# Find lots more stations at http://www.iheart.com' , '', '' ])
else:
tmp_stations.append([ '# Find lots more stations at http://www.iheart.com' , '' ])
tmp_stations.reverse()
try:
with open(st_new_file, 'w') as cfgfile:
writter = csv.writer(cfgfile)
for a_station in tmp_stations:
writter.writerow(self._format_playlist_row(a_station))
except:
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Cannot open playlist file for writing,,,')
return -1
try:
move(st_new_file, st_file)
except:
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Cannot rename playlist file...')
return -2
self.dirty_playlist = False
return 0 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/config.py#L258-L306 |
save list to file | python | def save_file(self, srcfile):
"""
Save a (raw) file to the store.
"""
filehash = digest_file(srcfile)
if not os.path.exists(self.object_path(filehash)):
# Copy the file to a temporary location first, then move, to make sure we don't end up with
# truncated contents if the build gets interrupted.
tmppath = self.temporary_object_path(filehash)
copyfile(srcfile, tmppath)
self._move_to_store(tmppath, filehash)
return filehash | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L501-L513 |
save list to file | python | def save(self, savefile):
"""Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
"""
with open(str(savefile), 'wb') as f:
self.write_to_fp(f)
log.debug("Saved to %s", savefile) | https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tts.py#L238-L250 |
save list to file | python | def save_file(path, data, readable=False):
"""
Save to file
:param path: File path to save
:type path: str | unicode
:param data: Data to save
:type data: None | int | float | str | unicode | list | dict
:param readable: Format file to be human readable (default: False)
:type readable: bool
:rtype: None
:raises IOError: If empty path or error writing file
"""
if not path:
IOError("No path specified to save")
try:
with io.open(path, "w", encoding="utf-8") as f:
if path.endswith(".json"):
save_json_file(
f,
data,
pretty=readable,
compact=(not readable),
sort=True
)
elif path.endswith(".yaml") or path.endswith(".yml"):
save_yaml_file(f, data)
except IOError:
raise
except Exception as e:
raise IOError(e) | https://github.com/the01/python-flotils/blob/5954712776bb590107e5b2f4362d010bf74f77a1/flotils/loadable.py#L352-L383 |
save list to file | python | def save(self, filename=None):
"""Save the document to file.
Arguments:
* filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from.
"""
if not filename:
filename = self.filename
if not filename:
raise Exception("No filename specified")
if filename[-4:].lower() == '.bz2':
f = bz2.BZ2File(filename,'wb')
f.write(self.xmlstring().encode('utf-8'))
f.close()
elif filename[-3:].lower() == '.gz':
f = gzip.GzipFile(filename,'wb') #pylint: disable=redefined-variable-type
f.write(self.xmlstring().encode('utf-8'))
f.close()
else:
f = io.open(filename,'w',encoding='utf-8')
f.write(self.xmlstring())
f.close() | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6547-L6568 |
save list to file | python | def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Saves html explanation to file. .
Params:
file_path: file to save explanations to
See as_html() for additional parameters.
"""
file_ = open(file_path, 'w', encoding='utf8')
file_.write(self.as_html(labels=labels,
predict_proba=predict_proba,
show_predicted_value=show_predicted_value,
**kwargs))
file_.close() | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L202-L221 |
save list to file | python | def xmlrpc_save2file(self, filename):
"""
Save results and own state into file.
"""
savefile = open(filename,'wb')
try:
pickle.dump({'scheduled':self.scheduled_tasks,
'reschedule':self.reschedule},savefile)
except pickle.PicklingError:
return -1
savefile.close()
return 1 | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L114-L125 |
save list to file | python | def save_to_filename(self, file_name, sep='\n'):
"""
Read all messages from the queue and persist them to local file.
Messages are written to the file and the 'sep' string is written
in between messages. Messages are deleted from the queue after
being written to the file.
Returns the number of messages saved.
"""
fp = open(file_name, 'wb')
n = self.save_to_file(fp, sep)
fp.close()
return n | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sqs/queue.py#L339-L350 |
save list to file | python | def save(self, fname=''):
"""
Save the list of items to AIKIF core and optionally to local file fname
"""
if fname != '':
with open(fname, 'w') as f:
for i in self.lstPrograms:
f.write(self.get_file_info_line(i, ','))
# save to standard AIKIF structure
filemap = mod_filemap.FileMap([], [])
#location_fileList = filemap.get_full_filename(filemap.find_type('LOCATION'), filemap.find_ontology('FILE-PROGRAM')[0])
object_fileList = filemap.get_full_filename(filemap.find_type('OBJECT'), filemap.find_ontology('FILE-PROGRAM')[0])
print('object_fileList = ' + object_fileList + '\n')
if os.path.exists(object_fileList):
os.remove(object_fileList)
self.lstPrograms.sort()
try:
with open(object_fileList, 'a') as f:
f.write('\n'.join([i[0] for i in self.lstPrograms]))
except Exception as ex:
print('ERROR = cant write to object_filelist ' , object_fileList, str(ex)) | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/programs.py#L88-L112 |
save list to file | python | def save_to_file_like(self, flo, format=None, **kwargs):
""" Save the object to a given file like object in the given format.
"""
format = self.format if format is None else format
save = getattr(self, "save_%s" % format, None)
if save is None:
raise ValueError("Unknown format '%s'." % format)
save(flo, **kwargs) | https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L65-L72 |
save list to file | python | def save(self, path=None, filter_name=None):
"""
Saves this document to a local file system.
The optional first argument defaults to the document's path.
Accept optional second argument which defines type of
the saved file. Use one of FILTER_* constants or see list of
available filters at http://wakka.net/archives/7 or
http://www.oooforum.org/forum/viewtopic.phtml?t=71294.
"""
if path is None:
try:
self._target.store()
except _IOException as e:
raise IOError(e.Message)
return
# UNO requires absolute paths
url = uno.systemPathToFileUrl(os.path.abspath(path))
if filter_name:
format_filter = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
format_filter.Name = 'FilterName'
format_filter.Value = filter_name
filters = (format_filter,)
else:
filters = ()
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XStorable.html#storeToURL
try:
self._target.storeToURL(url, filters)
except _IOException as e:
raise IOError(e.Message) | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1698-L1730 |
save list to file | python | def save(self, output=''):
"""Save the document.
If no output is provided the file will be saved in the same location. Otherwise output
can determine a target directory or file.
"""
self.file = self._get_output_file(output)
with open(self.file, 'w', encoding='utf-8') as f:
self.write(f) | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L84-L91 |
save list to file | python | def save_to(self, destination, name=None, overwrite=False, delete_on_failure=True):
"""
To save the object in a local path
:param destination: str - The directory to save the object to
:param name: str - To rename the file name. Do not add extesion
:param overwrite:
:param delete_on_failure:
:return: The new location of the file or None
"""
if not os.path.isdir(destination):
raise IOError("'%s' is not a valid directory")
obj_path = "%s/%s" % (destination, self._obj.name)
if name:
obj_path = "%s/%s.%s" % (destination, name, self.extension)
file = self._obj.download(obj_path,
overwrite_existing=overwrite,
delete_on_failure=delete_on_failure)
return obj_path if file else None | https://github.com/mardix/flask-cloudy/blob/8085d8fbbafec6c358f0d307bfcb795de50d4acb/flask_cloudy.py#L605-L624 |
save list to file | python | def save(self, incoming_stream, size_limit=None, size=None,
chunk_size=None, progress_callback=None):
"""Save file in the file system."""
fp = self.open(mode='wb')
try:
bytes_written, checksum = self._write_stream(
incoming_stream, fp, chunk_size=chunk_size,
progress_callback=progress_callback,
size_limit=size_limit, size=size)
except Exception:
fp.close()
self.delete()
raise
finally:
fp.close()
self._size = bytes_written
return self.fileurl, bytes_written, checksum | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/pyfs.py#L96-L114 |
save list to file | python | def save(self, path):
"""
Saving stored files at a given path (relative paths are added).
Args:
path (str): root path where to save the files.
"""
for relative_path_and_filename, content in self.files.items():
full_path_and_filename = os.path.join(path, relative_path_and_filename)
full_path = os.path.dirname(full_path_and_filename)
if not os.path.isdir(full_path):
os.makedirs(full_path)
with open(full_path_and_filename, 'wb') as handle:
handle.write(b64decode(content)) | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/memfiles.py#L57-L72 |
save list to file | python | def save_to_file(self, text, filename, name):
'''
Called by the engine to push a say command onto the queue.
@param text: Text to speak
@type text: unicode
@param name: Name to associate with the utterance
@type name: str
'''
self._push(self._driver.save_to_file, (text, filename), name) | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L178-L187 |
save list to file | python | def save(self):
"""Persist config changes"""
with open(self._config_file_path, 'w') as file:
self._config_parser.write(file) | https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/config.py#L140-L143 |
save list to file | python | def save_to_file(self, script_file):
""" Save filter script to an mlx file """
# TODO: rasie exception here instead?
if not self.filters:
print('WARNING: no filters to save to file!')
script_file_descriptor = open(script_file, 'w')
script_file_descriptor.write(''.join(self.opening + self.filters + self.closing))
script_file_descriptor.close() | https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/mlx.py#L201-L208 |