Dann239 last edited by
My first attempt at more than a simple action script. Feedback greatly appreciated. Spent many late nights reading and reading Python forums and the general documents. I thought I invented my own little clever way of writing and reading to the file. I had a short 2 line way of writing that wasn't tricky but the Remove def was more involved so in the interest of keeping my code consistent, I re wrote how I wanted it done so that it was similar to the remove def. My little code isn't as neat as some of the one line mind boggling pieces I have seen. Instead, I wanted it simple enough that I can read through it and explain it to someone.
PyList creates a file and writes to it. It sorts the list alphabetically as it is created. Critiques and comments encouraged.
ccc last edited by
with open('list', 'r') as f: lines = [line.strip() for line in open('list')]
Is strange syntax because you are opening the same file twice. The 'with open()' will automatically close the file when you exit the with clause. But the second open() will leave the file open indefinitely. I would propose an alternative syntax:
with open('list', 'r') as f: lines = [line.strip() for line in f]
Other things to watch for:
<li>When you see the same text repeated many times in a script, put it in a variable (filename = 'list') to make it easier to change the filename in the future.</li>
<li>When you see the same code repeated many times in a script, put it in a function (readlistfromfile()) to reduce program size while making code easier to understand / modify / debug / optimize in the future.</li>
<li>Avoid read / write global variables if at all possible. They carry global state that can often make bugs difficult to find. You may find it difficult to live without them in the beginning but keep thinking about ways to avoid them.</li>
For instance, comment out line 2 to get rid of the 'key' global variable.
Then comment out every line that contains 'global key' because we are going to use key only as a local variable.
Finally, change every line that says 'keyboard()' to say 'key = keyboard()'. Key is now a local variable that holds the user's keystrokes.
Personally, I would rename keyboard() to getuserinput() and rename key to userinput to increase readability.