I have 2 types of file types in a folder .docx/.doc and .pptx/.ppt, I have written a python script to cut and paste them into 2 folders one documents and the other powerpoints.
import os
FileTypeList = [".doc",".ppt"]
dirList = os.listdir(os.getcwd())
for FileType in FileTypeList:
for item in dirList:
if FileType in item:
print(True)
else:
print(False)
It always prints False. When I try:
if ".doc" in "document.docx":
print("True")
else:
print("False")
This prints True.
How can this be fixed?
from glob import glob
file_exts = ['*.doc', '*.ppt']
for ext in file_ext:
print(glob(ext))
glob.glob(pattern) will return a list of matched file names
FileTypeList
is a bad variable name.
Look at name wavic use
file_exts
,it's with underscore no CamelCase.
PEP 8.
Your code works fine for me. I switched it to .txt or .py, and in prints a bunch of Trues and Falses.
It is rather inefficient. You are checking each file twice, once to see if it's a Word doc, once to see if it's a PowerPoint file. It would be better to make a dictionary with file extensions as the keys, and folders they should be copied to as the values. Also, I would check with endswith rather than in. It's more precise and (again) more efficient.
import os
FileTypes = {'.txt': 'Text file','.py': 'Python program', '.xml': 'XML data'}
dirList = os.listdir(os.getcwd())
for item in dirList:
for extension, folder in FileTypes.items():
if item.endswith(extension):
print(folder)
break
else:
print('Other')
See how I used break? It only checks until it finds something, then it stops checking the other extensions. We can also use the else clause to catch anything to didn't match the extensions we were looking for.
I made a very minor error.
FileTypeList was actually coming from a file. Because it had \n at the end of the string the if statement returned false.
Now i did:
if FileType.rstrip() in item:
Blah
This returns true.
I did not post that.

My mistake. Sorry.