在Python中采用目录基名的优雅方法? [英] Elegant way to take basename of directory in Python?
问题描述
我有几个脚本以目录名称作为输入,我的程序在这些目录中创建文件。有时,我想使用赋予该程序的目录的基本名称,并使用该名称在目录中创建各种文件。例如,
I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example,
# directory name given by user via command-line
output_dir = "..." # obtained by OptParser, for example
my_filename = output_dir + '/' + os.path.basename(output_dir) + '.my_program_output'
# write stuff to my_filename
问题是,如果用户给目录名加上斜杠,则os.path.basename将返回空字符串,这不是我想要。在python中处理这些斜杠/尾部斜杠问题的最优雅方法是什么?我知道我可以手动检查output_dir末尾的斜杠,如果有的话可以将其删除,但是似乎应该有一个更好的方法。
The problem is that if the user gives a directory name with a trailing slash, then os.path.basename will return the empty string, which is not what I want. What is the most elegant way to deal with these slash/trailing slash issues in python? I know I can manually check for the slash at the end of output_dir and remove it if it's there, but there seems like there should be a better way. Is there?
还可以手动添加‘/’字符吗?例如。 output_dir +'/'os.path.basename()还是有更通用的方法来建立路径?
Also, is it OK to manually add '/' characters? E.g. output_dir + '/' os.path.basename() or is there a more generic way to build up paths?
谢谢。
推荐答案
要处理斜杠问题(以及其他问题!),请使用 os.path.normpath()清除用户输入。 / code>。
To deal with your "trailing slash" issue (and other issues!), sanitise user input with os.path.normpath()
.
要构建路径,请使用 os.path.join()
这篇关于在Python中采用目录基名的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!