Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Copyfile action
-
I wanted a simple, readily available way to make a copy of a file in the editor so I wrote the snippet below and added it as an action in the gear menu. I would love to learn if there is a better way to do this.
from shutil import copyfile import editor copyfile(editor.get_path(),editor.get_path().split(".")[0].split("/")[-1]+'.copy)
-
@ihf Good, thank you, very useful and short code!
I was waiting for something like that. Sorry but have you any idea how to copy entire folder?
Thanks
Bye -
Here is a script that will copy the folder that the file being edited is in. I had to test whether the file was in the root Documents, otherwise it would have copied everything. This will fail if you place your file in a folder named Documents (resulting in a path ending in Documents/Documents). Perhaps there is a better way to do this.
from shutil import copytree import editor if (editor.get_path().split('/')[-2] == 'Documents'): print 'Cannot copy Documents folder' else: copytree('/'.join(editor.get_path().split('/')[:-1]),'/'.join(editor.get_path().split("/")[:-1])+'.copy')
-
@ihf Hi, your script works well, thank you.
In order to copy entire folder or single file in any folder decided by user, it would be useful to query the current path of the opened folder in Pythonista file manager (not the path of the file or folder to be copied). Does a function exist in Pythonista?
Thanks
Bye -
@Matteo That's not possible as far as I know. However there's a different feature that might work well here - you can run shortcut scripts on files and folders in the file browser. Tap "Edit", select some files/folders, then tap on the wrench in the bottom toolbar. The wrench menu here is identical to the one in the editor, except for the paths that the selected script receives in
sys.argv
. If you use it from the editor, you get the path of the currently open file; if you use it from the file browser, you get the paths of all selected files/folders. -
@dgelessus Thanks for pointing that out. Here is a script which, if used as an action from the file manager, should copy any selected files and folders. I'm sure it can be improved but it seems to work.
import sys, os from shutil import copyfile from shutil import copytree import sys, os from shutil import copyfile from shutil import copytree for x in sys.argv[1:]: if os.path.isfile(x): copyfile(x, '.'.join(x.split("/")[-1].split('.')[:-1]) + '.copy') print 'Made copy of file:', x.split("/")[-1] else: if os.path.isdir(x): copytree('/'.join(x.split('/')), '/'.join(x.split("/")) + '.copy') print 'Made copy of directory:', x.split("/")[-1]
-
@dgelessus Thank you for the info, every time I discover a new thing related to Pythonista!
@ihf Very good, thank you for sharing your code! It is a very useful enhancement for Pythonista, especially for those who are learning to program in Python and needs to create copies of a library or foder containing scripts (for backup).
A simple idea to improve your script is to perform the copy-paste action in two steps instead of in one step, because the one step action pastes the file/folder in the same folder of the copied file/folder (this is ok but sometimes user needs to paste a file or folder in a different directory: he can use the built-in Move command but I think it would be more comfortable to stay in the main file manager page, the Move command opens a new sub-page with title "Move to..."):
- first step: script "A" (wrench action) to copy in ram/clipboard (or to create a hard copy in a temp folder inside main directory of Pythonista) any file or folder selected with Edit in file manager (@dgelessus hint);
- second step: script "B" (wrench action) to paste the existing file/directory in ram/clipboard (or move the hard copy of the copied file/folder) to the selected folder in file manager with Edit key.
Thank you all
Bye -
Hi, thanks to @ihf and based on his script, the following one creates a copy of file "x" in the same directory of "x". It works in the same way of the original script, as a wrench for File Browser.
Thank you @ihf for your useful script!#!python2 import sys, os from shutil import copyfile, copytree for x in sys.argv[1:]: if os.path.isfile(x): original_fullpath = os.path.dirname(x) original_filename = os.path.basename(x) original_filename_wo_ext = os.path.splitext(original_filename)[0] extension = os.path.splitext(original_filename)[1] copyfile(x, original_fullpath + '/' + original_filename_wo_ext + '_copy' + extension) print 'Made copy of file:', x.split("/")[-1] else: if os.path.isdir(x): copytree('/'.join(x.split('/')), '/'.join(x.split("/")) + '.copy') print 'Made copy of directory:', x.split("/")[-1]
-
Use tuple unpacking...
original_fullpath, original_filename = os.path.split(x) original_filename_wo_ext, extension = os.path.splitext(original_filename)
Also, print() is a function in modern Python. The legacy print statement (without the parens) should be avoided.
-
@ccc Thank you very much for your suggestions!
About it I ask if does a library exist that tries to rewrite a python code in a short way (with the objective to have the shortest code that performs the same operation of the long and readly friendly one. Thanks
Regards
-
Nope. That will continue to be a human activity until we get a bit closer to the Singularity. You could make big 💰 if you focused on shipping a great module that gets us over that event horizon.
-
@ccc 😊, you are right, it is a too difficult thing to do/have (a code that tries to write an other code in different ways according to a set of rules about python syntax and state of art typing).
I asked it only to have a learning tool that could help me to write python code in a short and user friendly way, a sort of optimization of the code before the execution, only for easy code reading by other people.
Thank anyway!
Regards -
@Matteo , I could be wrong. But I thought I had heard of something that helped refactoring your Python code to be more Pythonic. Hmmmm, I could be wrong. I did some quick searches but did not find anything. It's a hard thing to search for. I will look a little deeper. But It seems to be that it would certainly possible. Especially when you thing about some of the complex optimisations compilers continually do. You see glimpses of code simplification suggestions in PyCharm. I guess there are 2 ways to see it. Suggestions or the ability to do the refactoring of the code also.
But now you mention it, I am suprised there is not add ins like the PEP 8 checker that can make suggestions at least. I.e using context mangers with files, simplifying statements by using unpacking, comprehension optimisation suggestions etc.
With all the introspection built into Python, you would this would be an ideal language for doing these things.
Possibly one problem/blockage is Python is so easy to learn! But I here this on different pod casts all the time. And that is, yes Python is easy to learn, but mastering python is a totally different thing all together. Like writing a class is pretty simple at least on the surface. But when should you use class vars, static/class methods for example. You can read about all this stuff of course. But sometimes you dont even know some of these things exist. But it would seem to me some clever person could write code that looked at a class and make some suggestions about these things. Same as using properties or private/semi protected attrs.
I am not saying this would be easy code to write, more than likely would parse the source files more than once and maybe would not be that fast on big projects. But at least in my mind , a very cleaver python programmer with experience in language parsing could built a lib that would help with a lot of these things. As I say, even if it was intelligent suggestions possibly with examples or and references to relevant documentation.
Oh, i was just checking something while writing this. I wanted to see how if x <> 1:return was treated. You get a syntax error, but but not told to use != instead or <>. Then I used the Python 2 to 3 wrench item and Pythonista's implementation is very nice. I have never used it before :( But you could image a tool created for helping make your python more pythonic and pointing out optimisations could look something like that tool.
Sorry, long reply. I was just interested, as I would also love to have a tool that could help me write better python code.
One could say it may make you lazy and impede your learning. I am not so sure about that. @ccc convinced me to only write PEP8 code. I always use the Check Style and Analyse wrench menus to check my code. But since I started doing that religiously, I mostly just write PEP8 compliant code automatically. When I started seriously with this, the screen was lighting up everywhere with issues all over the place. Now, when I run the checks, I might have one or 2 small things to fix, but for the most part I have written it correctly. So just saying, automatic tools don't necessarily make you lazy or stop you learning. -
Thank you Phuket2 for your answer, I have read something about PEP8 (that in my very simplified lexicon is "how to write well python code") and I will try to follow as much as possible those suggestions.
About automatic tools for code analysis, yes, I'm agree with you and while sometimes automatic tools make us lazier, sometimes they help us because, if well done, they replace books, like having a book of good programming recipes summarized in a code.
This doesn't mean that books or years of programming are useless with these automatic tools for code checking, it means only that, since some people (like me) prefer to learn during problem solving and with practical exercises (best if these exercises are related to a real and practical problem, in this way one learns python programming and at the same time creates something useful for himself or for other people )) , the use of these tools is a fast and useful substitute for books, massive internet searching about how to write well a piece of code, etc...
Thanks
Regards -
I would say that PEP8 provides "style guidelines" for Python code.
It has been found that code that is formatted in a common way helps readers to understand the code faster. (Remember that the "reader" might be yourself months or years in the future.) Tools like autopep8 and Google's yapf automatically format code to aid readability. Many modern editors like Atom, etc. will automatically run these code formatters on each and every file save. The Go language leads the way by putting gofmt into the standard tool chain. Those who write Go say that this approach saves a lot of time and energy that gets wasted on style debates in code reviews, etc.
-
@ccc Wow, thank you! I will try autopep8 and YAPF for python. Ok, think to something that can be done in python: 99.99% already exists!
-
Google yapf v0.16.1 is built into Pythonista to drive wrench/Reformat Code...
-
@ccc Hi, thank you for hint, but I cant see reformat code. I use Pythonista 3.1 (301016). Is it a feature of Pythonista 3.2?
Bye
-
@Matteo , I think it was called 'Check Style' before. But I have no idea if it was using the same lib behind
-
@Phuket2 Hi, I have Check Style but it indicates the style issues of the code without any modification or reformat of the full script.
I try to perform some testsThank you