首页 > 解决方案 > 处理文件时如何在 Python 中创建 IF 语句?

问题描述

我正在努力处理文件。

我有两个这样的文件:

Document 1 987.docx
Document 1 Abc.docx

我有一个变量: x = "Document 1.docx"

我怎样才能创建一个if语句来说.. 如果在文件夹中出现两次Document 1.docx之后的任何随机单词,那么1Print("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"

标签: python

解决方案


您可以利用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!')

推荐阅读