简体   繁体   English

Python 测试给定文件夹路径中文件的给定路径

[英]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.

相关问题 给定一个hdfs路径,我怎么知道它是一个文件夹还是一个带有python的文件 - Given a hdfs path, how do I know if it is a folder or a file with python 在用户给定路径 PYTHON 中创建文件夹时出现 OSError - OSError in creating folder in a user given path PYTHON 使用python在给定的相对路径创建文件 - Create file at given relative path using python 如何正确应用 RE 以从给定路径获取姓氏(文件或文件夹的)并将其打印在 Python 上? - How to correctly apply a RE for obtaining the last name (of a file or folder) from a given path and print it on Python? 如何仅在 python 的给定路径中获取所有文件夹? - how to get all folder only in a given path in python? 检查给定路径中是​​否存在文件夹,如果不存在则在此处创建文件夹 - check if a folder exists in a given path and if not then create a folder there 解析具有给定掩码的文件路径 - parsing a file path with a given mask Python:搜索给定路径中的文件,但不搜索给定路径中目录中的文件 - Python: Search files in a given path but not the files in directories at given path 在Python中,如何获取给定文件路径的文件系统 - In Python, how can I get the file system of a given file path Python:检查给定路径中是​​否存在非目录文件 - Python: check for existence of a non-directory file at a given path
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM