[英]Python test given path to file in given path of folder
User input two strings, one is filename
and the other one is folder
.用户输入两个字符串,一个是
filename
,另一个是folder
。 The filename
variable is a path to some file on disk. filename
变量是磁盘上某个文件的路径。 And the folder
variable is a path to some folder on disk. folder
变量是磁盘上某个文件夹的路径。 I want to know if the file is located in the folder (either directly or in its sub folders).我想知道文件是否位于文件夹中(直接或在其子文件夹中)。
For example:例如:
isContains("C:\\a.txt", "C:\\") # True
isContains("C:\\a.txt", "C:\\a") # False
isContains("C:\\a.txt", "D:\\") # False
isContains("C:\\a\\b\\c\\d.txt", "C:\\") # True
isContains("C:\\a\\b\\c\\d.txt", "C:\\a\\b") # True
What I have done yet:我已经做了什么:
import os
isContains = lambda filename, folder: os.path.abspath(filename).startswith(os.path.join(os.path.abspath(folder), ''))
But I believe there must be some more elegant ways I didn't find out.但我相信一定有一些我没有发现的更优雅的方式。 As these code looks too complex.
因为这些代码看起来太复杂了。 How should I implement this function?
我应该如何实现这个 function?
My program is running on Windows.我的程序在 Windows 上运行。 But I want the code be platform independent.
但我希望代码独立于平台。
If you have no strict requirement to use os.path
, I'd recommend for all path-related work use pathlib
, it will save you lot of time.如果您对使用
os.path
没有严格要求,我建议所有与路径相关的工作都使用pathlib
,这将为您节省大量时间。
There's special method of Path
(PurePath
) class which does exactly what you're trying to implement - Path.is_relative_to()
.有
Path
(PurePath
) class 的特殊方法,它完全符合您的要求 - Path.is_relative_to()
。 Basically, you just need to initialize Path
from your filename
and call this method with folder
:基本上,您只需要从
filename
初始化Path
并使用folder
调用此方法:
Path(filename).is_relative_to(folder)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.