在处理文件时,如何在Python中创建IF语句?
我正在努力处理文件 我有两个这样的文件:在处理文件时,如何在Python中创建IF语句?,python,Python,我正在努力处理文件 我有两个这样的文件: 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
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!')
这听起来像是regex的工作:
import re
pattern = re.compile(r'^Document 1 ') #m
count = 0
for line in choices:
if pattern.search(line):
count += 1
if count >= 2: #use == if you only want doubles not triples
print("True")
这将捕获以“Document 1”开头并后跟空格的任何文件名,但不包括例如“Document 1name.docx”。对于这一点:
pattern = re.compile(r'^Document 1( |[a-z]|[A-Z]|[0-9])+\.docx$')
应该可以(只要没有标点符号)。请避免外部链接,并将此信息作为正确格式的文本包含在问题中。您好,谢谢您的回答。我在显示
if regex.search(line):TypeError:search()时出错,缺少1个必需的位置参数:“string”
,正如所写,选项应该是字符串列表。。。也许您正在使用re.search(行)
?在这种情况下,您将从模块调用搜索函数。。。请参阅编辑,即这也是可接受的格式:如果重新搜索(模式、行):
谢谢,它工作时没有任何错误,但没有返回任何内容。很遗憾,可能是glob正在为每个字符串添加路径名?尝试删除regex模式中的^
。还可以查看re模块的pydocs。