python - 处理文件时如何在 Python 中创建 IF 语句?
问题描述
我正在努力处理文件。
我有两个这样的文件:
Document 1 987.docx
Document 1 Abc.docx
我有一个变量:
x = "Document 1.docx"
我怎样才能创建一个if
语句来说.. 如果在文件夹中出现两次Document 1.docx
之后的任何随机单词,那么1
Print("True")
这就是我要去的地方:
import os
import glob
directory = "C:/Users/hawk/Desktop/Test" # directory
choices = glob.glob(os.path.join(directory, "*")) # returns all files in the folder
print(choices) #shows all files from the directory
x = "Document 1.docx"
解决方案
您可以利用glob
语法过滤文件,然后检查是否找到任何内容:
import glob
import os
filename_prefix = 'Document 1'
# For simplicity, I'm just using current directory.
# This can be whatever you need, like in your question
directory = '.'
# Looks for any files whose name starts with filename_prefix ("Document 1")
# and has a "docx" extension.
choices = glob.glob(os.path.join(directory, '{prefix}*.docx'.format(prefix=filename_prefix)))
# Evaluates to True if any files were found from glob, False
# otherwise (choices will be an empty list)
if any(choices):
print('Files with', filename_prefix, 'found!')
推荐阅读
- amazon-web-services - 将 !Sub 与 !GetAtt 以 YAML 格式结合
- go - 使用 URL 下载 zip 文件
- regex - 基于其他字符串变量在新变量中提取字符串模式
- git - git filter-branch:通过排除过滤目录,不包括?
- javascript - 如何解决:“TypeError:无法读取 null 的属性‘打印类型’”
- macos - Jenkins 通过 docker:如何将自己的主机配置为 jenkins 的代理?
- sql-server - 我有两个表我需要一个查询来组合这两个表并按键 A、键 B、键 C、日期、时间对它们进行排序
- python-3.x - 如何遍历列表以在 Pandas 数据框中查找值
- javascript - 如何减少蓝色框出现在文本周围的次数?
- angular - TypeError:provideModuleMap 不是一个函数~ NestJS