Greetings!
I'm trying to copy files if the file name has a digit and it is in the range of 0-3.
files in a directory go like this:
file.txt
file-1.txt
file-2.txt
file-3.txt
...
file-50.txt
the snippet I have does not print anything for some reason.
from pathlib import Path
import re
dr ='C:\01'
for ef in Path(dr).iterdir() :
fn = Path(ef).stem
#print(f" Names -> {fn}")
num = re.findall(r'\d+', fn)
#print(f" Digit -> {num} - {fn}")
if num in range(0,3) :
print(f" File to copy -> {ef}")
Thank you!
If you un-comment your debug line (9), you should be able to see what's going on: num
is a list object and as such, the if
at line 10 is never going to return True
.
Also, if/when the num
list is populated, it's populated with a str
object, so there's that also.
I missed that part! Thank you for pointing!
It will never find folder
C:\01
>>> dr ='C:\01'
>>> dr
'C:\x01'
See the problem?
So like this.
>>> dr = r'C:\01'
>>> dr
'C:\\01'
>>> # Or
>>> dr = 'C:/01'
>>> dr
>>> 'C:/01'
To show a way with regex.
>>> import re
>>>
>>> s = 'file-1.txt'
>>> re.search(r'.*[1-3]', s)
<re.Match object; span=(0, 6), match='file-1'>
>>> s = 'file-3.txt'
>>> re.search(r'.*[1-3]', s)
<re.Match object; span=(0, 6), match='file-3'>
>>> s = 'file-5.txt'
>>> re.search(r'.*[1-3]', s)
>>> #No match
Then like this.
from pathlib import Path
import re
dr = r'C:\bar'
for ef in Path(dr).iterdir():
if re.search(r'.*[0-3]', ef.stem):
print(ef)
Output:
C:\bar\file-1.txt
C:\bar\file-2.txt
C:\bar\file-3.txt
I still cannot find files in range.
for enum in num :
if enum in range(0,3) :
print(f" File to copy -> {ef}")
I got your script to work by altering it a little, to match my system, so you may want to take note of what @
snippsat has posted
This is is what I've run:
from pathlib import Path
import re
dr = '/home/rob/Desktop/python/temp'
for ef in Path(dr).iterdir():
fn = Path(ef).stem
num = re.findall(r'\d+', fn)
if num:
num = int(num[0])
if num in range(0, 3):
print(f" File to copy -> {ef}")
Output:
File to copy -> /home/rob/Desktop/python/temp/file-2
File to copy -> /home/rob/Desktop/python/temp/file-1
snippsat, thank you for the snipped!
For some reason, the snippet also prints other files that start with digits "1", "2" or "3"
Like file-33.txt and so on...
rob101! It works!
You are oficcialy DA MAN now!
Of course "snippsat" is DA BOSS but you are OK too!
Thank you guys!

(Nov-23-2022, 11:09 PM)tester_V Wrote: [ -> ]Like file-33.txt and so on...
Change regex to this.
if re.search(r'.*\b[1-3]\b', ef.stem):
Well 'snippsat', you are DA MAN too brother... DA MAN!
