【发布时间】:2015-07-10 21:31:17
【问题描述】:
我正在尝试创建一个将自身复制到另一个位置并在桌面上创建批处理文件的程序。我可以让它自己复制,我可以创建批处理文件,但我需要一些有关路径的帮助。
我可以找到我的程序当前所在的路径。直接路径和目录路径。我的问题在于我想将文件放在(为了简单起见)'C:\Users\Me\Documents'。我将如何编辑路径?我希望能够将其放置在通用 Windows 计算机上,因此我无法硬编码路径,因为每个用户都会有所不同。放置批处理文件并将其设置为正确的目录以在文档中运行 python 脚本也是如此。
我都试过了
import os
print os.path.dirname(os.path.abspath(__file__))
和
import os
print os.path.abspath(__file__)
但我对如何编辑路径一无所知。当我尝试用谷歌搜索它并搜索这个精彩的网站时,我得到的只是关于在 Windows 上配置 Python 路径的内容以及我目前的 Python 水平还不太理解的其他内容。
现在我转向你,你能帮忙吗?如果您能解释它是如何工作的,那么任何输入都将不胜感激!
由于对我的代码(以及要发布的特定代码)的一些问题,这里是
from sys import argv # Imports module
import os
script, create = argv # Gets script name and desired amount of copies
data = open(script) # Creates a variable to store the script
indata = copy.read() # Creates the data to be copied from the script
batData = """
echo off
%s
""" % # This is not finished, creating that batch file
createT = int(create) + 1
for i in range(1, createT): # Runs a set amount of times
copyName = "%s.py" % str(i) # Creates the name for the file
copy = open(copyName, 'w+') # Opens/creates the file for editing
copy.write(indata) # Writies the indata to the file opened
copy.close # Closes that file
batName = "%s.bat" % str(i)
bat = open(batName, 'w+')
它没有完成,但希望你能明白要点。开头的 argv 是为了让我可以更改制作的副本数量,稍后我会随着代码的发展将其删除,但现在我喜欢它。
我目前已尝试以下方法来查找路径:
import os
print os.path.abspath(__file__)
print os.path.dirname(os.path.abspath(__file__))
print os.path.dirname(__file__)
test = os.path.dirname(__file__)
a, b, c, d, e, f, g, h, i = test.split("\\")
print c
我想要发生的(或认为我想要发生的)是找到路径,然后分成几部分(每个目录或在用户名之后断开所有内容)。然后我想将文档文件夹标签附加到末尾。对于批处理而不是文档标签,它将用于桌面。
在人们发布的其他一些内容中。我希望这会有所帮助!
【问题讨论】:
-
与批处理文件标签的关系在哪里?
-
我正在使用:
batName = "%s.bat" % str(i); bat = open(batName, 'w+')创建文件。这有帮助吗? -
“编辑路径”是什么意思?您想为用户提供一个输入字段以输入新路径,还是想从命令行中提取它,或者以某种方式计算它?您如何确定新路径是什么?
-
我想要一种方法来编辑我可以从
os.path.dirname(os.path.abspath(__file__))获取的内容我希望它是自动的,所以当程序运行时不需要任何输入。 -
@JakeT,由于您的术语,您可能没有通过搜索找到任何东西——“编辑路径”通常意味着更改系统 PATH(操作系统或 Python 的)。在您的具体情况下,请参阅我上面链接的问题;一般来说,您可以使用 os.path 方法——例如,您可以使用
os.path.dirname()来回退一个目录。路径只是一个字符串,因此您可以通过字符串连接 (... + '/build') 添加路径组件。然后你可以将它传递给open()、os.chdir()等,这取决于你想要做什么。
标签: python windows batch-file path