将 .py 保存到文件本身的另一个目录中的脚本 [英] script to save a .py into another directory within the file itself

查看:45
本文介绍了将 .py 保存到文件本身的另一个目录中的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在名为 directory1 的目录中创建了一个名为 file.py 的文件.运行 file.py 时,有没有办法让 file.py 将它自己的脚本保存到另一个目录,比如 directory2,作为 .txt 文件或 .py 文件?

Let's say I create a file called file.py in a directory called directory1. When running file.py, is there a way I can have file.py save it's own script to another directory, say directory2, as a .txt file or a .py file?

谢谢!

推荐答案

一般来说,如果您使用编辑器编写代码,您可以将其保存到另一个具有不同文件扩展名的目录中.但是我猜对了,您想在不同的目录中获得备份吗?这取决于您的编辑器,现在大多数人都会这样做.

generelly, if you're using an editor to write the code, you could just save it to another directory with different file extension. But do I guess right that you want to get a backup in a different direcotry? It depends on your editor, most will do that nowadays.

但确保您可以在文件中编写类似的内容,只需将其复制到您选择的目录中即可:

But sure you can write something like this in your file which just copies it to a dir of your choice:

import os, shutil

if not os.access(dirname, os.F_OK):
    os.mkdir(dirname, 0o700)

shutil.copy(fname, dirname)

这段代码的作用是,如果它不存在,它首先创建一个目录,jet,并赋予它读、写和执行权限.然后它复制 fname 的内容,其中包含文件本身的文件名并将其复制到您刚刚创建的目录中.

What this code does is, it first creates a directory if it doesn't exist, jet, and gives it read, write and execute permissions. Than it copies the content of fname, which contains the file name of the file itself and copies it to the directory you just created.

但是你为什么要将最近编写的代码复制到不同的位置?

But why woul you copy the recent code you just wrote to a different location?

为了跟踪您的工作,有更好的方法来做到这一点,例如版本控制系统,如 darcs、subversion(又名 svn)或 gitorious(主要基于网络).它们使用不同的版本号保存您的工作,您不必在每次达到里程碑时更改文件名.如果您选择获取早期版本,它们会帮助您打开分支、稍后加入它们并保持您的代码可执行.

For keeping track of your work, there are better ways to do that, for example version control systems like darcs, subversion (aka svn) or gitorious (which is mainly webbased). They save your work with different version numbers and you don't have to alter the file names each time you achieved a milestone. They help you opening up branches, join them later and keep your code executable if you choose to get an earlier version.

与:

fname = "work_today.txt"

您可以将代码保存为新的文件名,即使是它包含的文件的相同代码.您必须正确更改文件名,切断扩展名并连接新字符串.——

you can save the code, even the very same code of the file it contains, to new file name. you have to alter the filename correctly, cut off the extension and concatenate the new string. –

这篇关于将 .py 保存到文件本身的另一个目录中的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆