I need to check a condition, and based on the condition perform a very similar for
-loop.
import os
folder = r'path'
folder_list = os.listdir(folder)
folder2 = r'path/folder2'
args = True
the_list = []
if args is True:
for x in folder_list:
if x.endswith('.txt'):
if not os.path.exists(os.path.join(folder2, x)):
full_path = os.path.join(folder, x)
the_list.append(full_path)
else:
for x in folder_list:
if x.endswith('.txt'):
full_path = os.path.join(folder, x)
the_list.append(x)
I would like to avoid having the redundant for
-loop code if possible.
I originally had the following, which I wasn't happy with because args
was being checked every single iteration, which is unnecessary.
import os
folder = r'path'
folder_list = os.listdir(folder)
folder2 = r'path/folder2'
args = True
the_list = []
for x in folder_list:
if x.endswith('.txt'):
full_path = os.path.join(folder, x)
if args['i'] is True:
if not os.path.exists(os.path.join(folder2, x)):
the_list.append(full_path)
else:
the_list.append(full_path)
args
if you set it yourself toTrue
? \$\endgroup\$'i'
? Please show your actual code, the code you've posted here doesn't actually run. \$\endgroup\$else
part you appendx
tothe_list
, while in the second version you appendfull_path
. \$\endgroup\$if
and theelse
part, but to the difference between the first and second version of the code shown. \$\endgroup\$