Since here we have a certain “review” of conservation methods, I will allow myself some addition.
The first. From the above saving options, the slowest option on large files is file.write("\n".join(ips)) . And it will simply “eat” the memory when combined into one giant string variable. The other two are the same in speed and result.
The second. Usually they save data in a file in order to later read or transfer it to an external user. If the first option is supposed to be “I wrote it down myself then I read it myself”, then saving serialization using the modules pickle, json, shelve is much more efficient.
import pickle ips = ['10.10.10.98', '10.10.10.99'] with open('ips.pickle', 'wb') as f: pickle.dump(ips, f)
which will allow later to "restore" the entire list into a variable, without thinking about how you will parse the lines in ips:
with open('ips.pickle', 'rb') as f: ips = pickle.load(f) print(ips)
json is usually slower, but it retains in almost standard json format, which is more humane - it can be opened and understood - what’s preserved there. There are some more serialization libraries with their own features, such as: jsonpickle , simplejson , demjson . All of them use the json format, and in their own way extend the capabilities of the standard json- module included in the Python distribution.
The fastest, but dependent on the version of the serialization language, is achieved by the built-in marshal module. The code is almost the same:
import marshal ips = ['10.10.10.98', '10.10.10.99'] with open('ips.pickle', 'wb') as f: marshal.dump(ips, f) with open('ips.pickle', 'rb') as f: ips = marshal.load(f) print(ips) ['10.10.10.98', '10.10.10.99']