Asked  7 Months ago    Answers:  5   Viewed   33 times

I have looked through the information that the Python docs give, but I'm still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it?

 Answers

25

Try this:

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)

print a == b
Tuesday, June 1, 2021
 
Evernoob
answered 7 Months ago
37

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.

Wednesday, June 9, 2021
 
daiscog
answered 6 Months ago
48

The official way to mark a shortcut file as requiring elevation is via IShellLinkDataList. It's difficult to use that interface from an automation environment.

But, if you are happy with a hack, you can do it in script, just by flipping a bit in the .lnk file.

When you tick the "run as administrator" box in the Advanced tab of the Shell Properties box, or when you use IShellLinkDataList to set the flags to include SLDF_RUNAS_USER, you're basically just setting one bit in the file.

You can do that "manually" without going through the COM interface. It's byte 21, and you need to set the 0x20 bit on.

(function(globalScope) {
    'use strict';
    var fso = new ActiveXObject("Scripting.FileSystemObject"),
        path = "c:\path\goes\here\Shortcut2.lnk",
        shortPath = path.split('\').pop(),
        newPath = "new-" + shortPath;

    function readAllBytes(path) {
        var ts = fso.OpenTextFile(path, 1), a = [];
        while (!ts.AtEndOfStream)
            a.push(ts.Read(1).charCodeAt(0));
        ts.Close();
        return a;
    }

    function writeBytes(path, data) {
        var ts = fso.CreateTextFile(path, true),
            i=0, L = data.length;
        for (; i<L; i++) {
            ts.Write(String.fromCharCode(data[i]));
        }
        ts.Close();
    }

    function makeLnkRunAs(path, newPath) {
        var a = readAllBytes(path);
        a[0x15] |= 0x20; // flip the bit. 
        writeBytes(newPath, a);
    }

    makeLnkRunAs(path, newPath);

}(this));

ps:

function createShortcut(targetFolder, sourceFolder){
    var shell = new ActiveXObject("WScript.Shell"),
        shortcut = shell.CreateShortcut(targetFolder + "\Run The Script.lnk"),
        fso = new ActiveXObject("Scripting.FileSystemObject"),
        windir = fso.GetSpecialFolder(specialFolders.windowsFolder);

    shortcut.TargetPath = fso.BuildPath(windir,"system32\cscript.exe");
    shortcut.Arguments = """ + sourceFolder + "\script.js" /aParam /orTwo";
    shortcut.IconLocation = sourceFolder + "\icon.ico";
    shortcut.Save();
}
Friday, July 30, 2021
 
John_BSDthos
answered 5 Months ago
29

You need to pull the list from your database (i.e. your pickle file) first before appending to it.

import pickle
import os

high_scores_filename = 'high_scores.dat'

scores = []

# first time you run this, "high_scores.dat" won't exist
#   so we need to check for its existence before we load 
#   our "database"
if os.path.exists(high_scores_filename):
    # "with" statements are very handy for opening files. 
    with open(high_scores_filename,'rb') as rfp: 
        scores = pickle.load(rfp)
    # Notice that there's no "rfp.close()"
    #   ... the "with" clause calls close() automatically! 

first_name = input("Please enter your name:")
score = input("Please enter your score:")

high_scores = first_name, score
scores.append(high_scores)

# Now we "sync" our database
with open(high_scores_filename,'wb') as wfp:
    pickle.dump(scores, wfp)

# Re-load our database
with open(high_scores_filename,'rb') as rfp:
    scores = pickle.load(rfp)

print(scores)
Wednesday, August 11, 2021
 
John Oleynik
answered 4 Months ago
91

As monkey said: You don't want to pickle a surface. But if you really need to save that surfaces' content than use the pygame.image.save() function.

If you prefer your surface not to be an actual image file (for whatever reason) you could use the pygame.image.tostring() function which lets you convert the surfaces' content into a stringbuffer.

Friday, October 22, 2021
 
user123444555621
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share