mlh*_*789 8 python operating-system
我正在编写样板,处理命令行参数,稍后将传递给另一个函数.这个其他函数将处理所有目录创建(如果需要).因此我的bp只需要检查输入字符串是否是有效目录,或者是有效文件,还是其他东西.即它需要区分"c:/ users/username /"和"c:/users/username/img.jpg"之类的东西
def check_names(infile):
#this will not work, because infile might not exist yet
import os
if os.path.isdir(infile):
<do stuff>
elif os.path.isfile(infile):
<do stuff>
...
Run Code Online (Sandbox Code Playgroud)
标准库似乎没有提供任何解决方案,但理想的是:
def check_names(infile):
if os.path.has_valid_dir_syntax(infile):
<do stuff>
elif os.path.has_valid_file_syntax(infile):
<do stuff>
...
Run Code Online (Sandbox Code Playgroud)
在打字时考虑问题之后,我无法理解一种检查(仅基于语法)字符串是否包含除文件扩展名和尾部斜杠之外的文件或目录(两者都可能不存在)的方法.可能刚刚回答了我自己的问题,但是如果有人想到我的随意,请发帖.谢谢!
我不知道你正在使用什么操作系统,但问题是,至少在Unix上,你可以拥有没有扩展名的文件.所以~/foo可以是文件或目录.
我认为你能得到的最接近的是:
def check_names(path):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18063 次 |
| 最近记录: |