Run code on specific files in a directory separately (by the name of file)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Run code on specific files in a directory separately (by the name of file)



I have N files in the same folder with different index numbers like


Fe_1Sec_1_.txt
Fe_1Sec_2_.txt
Fe_1Sec_3_.txt

Fe_2Sec_1_.txt
Fe_2Sec_2_.txt
Fe_2Sec_3_.txt
.
.
.
and so on



Ex: If I need to run my code with only the files with time = 1 Sec, I can make it manually as follow:


path = "input/*_1Sec_*.txt"
files = glob.glob(path)
print(files)



which gave me:


Out[103]: ['input\Fe_1Sec_1_.txt', 'input\Fe_1Sec_2_.txt', 'input\Fe_1Sec_3_.txt']



In case of I need to run my code for all files separately (depending on the measurement time in seconds, i.e. the name of file)

I tried this code to get the path for each time of measurement:


time = 0
while time < 4:
time += 1
t = str(time)
path = ('"input/*_'+t+'Sec_*.txt"')



which gives me:


"input/*_1Sec_*.txt"
"input/*_2Sec_*.txt"
"input/*_3Sec_*.txt"
"input/*_4Sec_*.txt"



After that I tried to use this path as follow:


files = glob.glob(path)
print(files)



But it doesn't import the wanted files and give me :


"input/*_1Sec_*.txt"

"input/*_2Sec_*.txt"

"input/*_3Sec_*.txt"

"input/*_4Sec_*.txt"



Any suggestions, please??





are you accessing your path string inside the while loop? If yes, can you show the updated code and error msg if any?
– mad_
Aug 6 at 15:18


path





@mad_ This is the msg "input/*1Sec.txt" "input/2Sec.txt" "input/3Sec.txt" "input/4Sec*.txt"
– H. H
Aug 6 at 16:01





@mad_ you can see the msg in my edit of question
– H. H
Aug 6 at 16:03




1 Answer
1



I think the best way would be to simply do


for time in range(1, 5): # 1,2,3,4
glob_path = 'input/*_Sec_*.txt'.format(time)
for file_path in glob.glob(glob_path):
do_something(file_path, measurement) # or whatever





I wonder what is the difference in this piece of code and what OP has posted except string formatting and for->while loop.
– mad_
Aug 6 at 15:14





@FHTMitchell_ it doesn't work
– H. H
Aug 6 at 16:18






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered