'Can't get matching in an "if" statement
This is my first time posting a question on stackoverflow and I'm new to programming in general. Any guidance on the below matter will be appreciated.
I have a bit of code I've been trying to get working for roughly a week without luck on this section.
for sitem in os.listdir(inputpath):
filename = os.path.basename(sitem.split(sep,)[0])
#print (filename)
for ditem in os.listdir(destpath):
#print(filename, ditem)
#break
if filename.lower() == ditem.lower():
print(f"{filename} matched {ditem}")
In the code above I am trying to iterate through two folders one with some source files (from inputpath
) which I plan to move to a matching folder name in the destination (destpath
). The idea is that the first for
loop variable (sitem
) should contain the first item in source folder. Then the second second for
loop should cycle through the destination folder all with the sitem
being the first item in the source. The if
statement should match once it gets to filename and ditem
being the same.
Problem I am having is that the if
statement will not match. Once I have a match I plan to add the rest of the path using os.path.join
to get the full path to then move the file using shutil
.
inputpath
and destpath
are variables I have pointed to a network path on my system and the scan of these files work perfectly fine.
I have used various print/break statements in different parts of the code to verify that the outputs are correct and that the folder name and filename are OK. For example I would make a print(f"{filename} does not match {ditem})
with a break
and change the if
statement to !=
and the output would be something like 100 humans does not match 100 humans
which shows the name source files name (100 humans) and the foldername (100 Humans) does match.
I have also tried bringing the if
statement out of the second for
loop and into the first and that also did not bring any result of note.
Solution 1:[1]
for sitem in os.listdir(inputpath):
filename = os.path.basename(sitem.split(sep,)[0])
stripped = filename.strip()
#print (filename)
for ditem in os.listdir(destpath):
foldername = ditem.strip()
#print(filename, ditem)
#break
if stripped == foldername:
copy_to = os.path.join(destpath, foldername)
copy_from = os.path.join(inputpath, sitem)
shutil.move(copy_from, copy_to)
print(f"{sitem} moved to {copy_to}")
#print (filename, foldername)
The code above worked for what I was trying to do. I think the original issue was some whitespace being left over in the filename. made a new variable called stripped to hold the filename with all whitespace removed.
Thank you everyone for your help. reading each comment got me thinking in different ways and it helped greatly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | skech |