是否可以在 Python 脚本中创建动态路径?
我的想法是,我有多个目录,每个目录中都有随机数量的文件。目前,我有一个工作脚本,可以将其复制到每个目录中并运行,它将根据我的喜好重命名该目录中的每个文件。
这是我的痛点:如果我要将此脚本复制到另一个目录,我必须更改脚本中的路径,以便它重命名正确目录中的文件。如果我不更改脚本中的路径,它将重命名以前目录中的文件,这不是我的意图。
我的问题是:我可以在脚本中创建动态引用,以便脚本更新自己的路径,从而重命名预期目录中的文件吗?这样,我只需将脚本复制到新目录并运行它。
我正在使用 os.rename() 来重命名我的文件。
os.rename 使用带有前缀“r”的路径。这是我如何使用 os.rename() 执行此操作的示例:
python
folder = r'M:\Python Projects\Rename Files\Repo\\'
source = folder + file_name
destination = folder + d + " " + lookup_table[lookup_val] + ".pdf"
os.rename(source, destination)
我希望我的 folder 变量是动态的。因此,例如,当我将脚本复制到另一个目录时,文件夹将是当前目录的路径。
The idea is, I have various directories with a random number of files in each directory. Currently, I have a working script that I can copy into each dir and run and it will rename each file in that dir to my liking.
Here is my pain point: If I were to copy this script to another dir, I would have to change the path within my script so it renames the files in the correct directory. If I do not change the path in my script, it will rename files from the previous dir, which is not my intention.
My question is: can I create a dynamic reference in my script so that the script will update its own path so it will rename the files in the intended dir? This way, I will only have to copy the script to the new dir and run it.
I am using os.rename() to rename my files.
os.rename is using a path that has a prefixed 'r'. This is an example of how I am doing this with os.rename():
python
folder = r'M:\Python Projects\Rename Files\Repo\\'
source = folder + file_name
destination = folder + d + " " + lookup_table[lookup_val] + ".pdf"
os.rename(source, destination)
I would like my folder variable to be dynamic. So for example when I copy the script over to another dir, folder would be the path of the current dir.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用:
os.getcwd()
来自 python-get-current-directory
Use:
os.getcwd()
From python-get-current-directory