Hakws Eye
Hakws Eye

Reputation: 3

How to create an IF statement in Python when working with files?

I am struggling to work with files.

I have two files like this:

Document 1 987.docx
Document 1 Abc.docx

I have a variable: x = "Document 1.docx"

How can I create an if statement to say.. If Document 1.docx with any random word after the 1 appears twice in the folder, then Print("True")

This is where I got to:

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"

Upvotes: 0

Views: 1304

Answers (2)

neutrino_logic
neutrino_logic

Reputation: 1299

It sounds like a job for 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")

This will capture any filename beginning with "Document 1" followed by a space, but not for example "Document 1name.docx". For that something like:

pattern = re.compile(r'^Document 1( |[a-z]|[A-Z]|[0-9])+\.docx$')

Should work (as long as there's no punctuation).

Upvotes: 0

b_c
b_c

Reputation: 1212

You can utilize the glob syntax to filter down your files, then just check if anything was found:

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!')

Upvotes: 1

Related Questions