? Editing: Post:21.body Save Delete Cancel
Content changed Sign & Publish new content

cgm616

trying out this distributed thing


Latest comments:

Add new post

Title

21 hours ago · 2 min read 2
Body
Read more

Starting to learn python

on Dec 13, 2015

Just started to learn python. I know general programming concepts, but not Python specifically or its syntax, so this was new for me. I love it. Coolest thing? for line in file: This is so great.

Anyways, I made a python script, that when run, creates a copy of itself in the same directory. I think it's pretty cool.

import os
import binascii

def replicate(path):
    #
    # Replicate a file given the path of the current file.  Opens current file
    # and new file and reads all lines into new file.
    #
    with open(get_new_filename(path), "w") as newfile, open(path) as program:
        for line in program:
            newfile.write(line)


def get_new_filename(old_name):
    #
    # Gets a new filename given a filename to work off of.  Splits the old name
    # by periods, then adds a random hex string right before the filetype
    # ending.  Given 'files.py', a valid output would be 'files-2b57f5.py'.
    #
    # The function also checks for collisions and adds another random string to
    # the end if necessary.
    #
    # http://stackoverflow.com/a/2782293
    #
    broken_name = old_name.split('.')
    while True:
        ending = '-' + str(binascii.b2a_hex(os.urandom(3))).replace('\'', '')
        broken_name[-2] = broken_name[-2] + ending
        name = '.'.join(broken_name)
        if not os.path.exists(name):
            break
    return name


if __name__ == '__main__':
    replicate(__file__)

I want to do something with my new knowledge, but I don't know what. I think an entire os made of python would be pretty cool, but my skills are definitely not at the level, and python might be too high level and slow.

2 Comments:

user_name1 day ago
Reply
Body
cgm616on Dec 20, 2015
Reply

muja: Relevant xkcd: https://www.xkcd.com/353

That is actually what it feels like, no joke.

mujaon Dec 20, 2015
Reply

Relevant xkcd: https://www.xkcd.com/353

This page is a snapshot of ZeroNet. Start your own ZeroNet for complete experience. Learn More