How to pythonically avoid this code duplication with a while loop?
I want to find the first filename
myfile????.txt that doesn't exist yet (
???? is a number). This works:
import os i = 0 f = 'myfile%04i.txt' % i while os.path.exists(f): i += 1 f = 'myfile%04i.txt' % i
but I don't like the code duplication of
f = ....
Is there a pythonic way to avoid the code duplication in this
NB: I have posted a half-satisfactory solution, using a
do/while idiom, as mentioned in the main answer of Emulate a do-while loop in Python?, but I still wonder if there is better way for this particular case (thus, it's not a dupe of this question).
You do not need to follow the
while paradiagm here, a nested generator expression with
import os from itertools import count f = next(f for f in ('myfile%04i.txt' % i for i in count()) if not os.path.exists(f)) print(f)
Using a closure to avoid code duplication in Python, It is a an acceptable form. As @Giorgio said, I would put the closure after the captured variable definition to ease the flow of reading. The alternative form would How to pythonically avoid this code duplication with a while 1 1
Get rid of the
import os i = 0 while os.path.exists('myfile%04i.txt' % i): i += 1
PEP 315 -- Enhanced While Loop, It is possible to prevent code duplication by moving the loop condition into a helper function, or an if statement in the loop body. However The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. The break Statement With the break statement we can stop the loop even if the while condition is true:
I nearly found the answer while writing the end of the question. After a few modifications, it works:
import os i = 0 while True: f = 'myfile%04i.txt' % i if not os.path.exists(f): break i += 1 print f
Still I wonder if there is a more pythonic way, maybe with an iterator, generator,
next(...) or anything like this.
Python Refactoring: "while True" Infinite Loops & The "input , In this video I'm refactoring some Python code that a reader sent me over Twitter and asked me Duration: 17:47 Posted: Jun 27, 2017 The code that is in a while block will execute as long as the while statement evaluates to True. You can think of the while loop as a repeating conditional statement. After an if statement, the program continues to execute code, but in a while loop, the program jumps back to the start of the while statement until the condition is False.
Is this too simple?
import os f = 'myfile0000.txt' while os.path.exists(f): i += 1 f = 'myfile%04i.txt' % i
Code Style, One reason for the high readability of Python code is its relatively complete set of Code Style guidelines and “Pythonic” idioms. Those two possibilities are better avoided without any strong reason to not It will help to flatten the structure of the function: all the code after the return-because-of-error statement can assume True/False: The first line in the while loop is referred to as the condition clause. D. condition-controlled loop What type of loop structure repeats the code based on the value of the Boolean expression?
You could do:
import os from itertools import count cursor = count() it = iter((path for path in map(lambda x: 'myfile%04i.txt' % x, cursor) if not os.path.exists(path))) first = next(it, None) if first: print(first)
The Hitchhiker's Guide to Python: Best Practices for Development, Best Practices for Development Kenneth Reitz, Tanya Schlusser in tablib/formats/—it's a perfect example of the statement we made earlier about not overusing classes. registers file formats to avoid duplicating what would be boilerplate code for each of You can skip these sections and still lead a happy, Pythonic life. I challenge you to avoid writing for-loops in every scenario. Also, I challenge you to find the scenarios that are so freaking hard to write anything else but a for-loop. Please share your findings.
Modern Accelerator Technologies for Geographic Information Science, While it is not possible to make a pythonic view of the shared memory space First, we avoid the use of memory duplication by passing a pointer and row indices Second, we remove all for loops from the code to leverage vectorization in the Loop programming exercises and solutions in C June 20, 2015 Pankaj C programming C , Exercises , Loop , Programming In programming, there exists situations when you need to repeat single or a group of statements till some condition is met.
Effective Python › Item 10: Prevent Repetition with Assignment , For example, say that I have a basket of fresh fruit that I'm trying to manage of lemons and then using an if statement to check for a non-zero value: The problem with this seemingly simple code is that it's noisier than it needs to be. Effective Python: Second Edition provides insight into the Pythonic way Python Tutorial 11 Looping your code back to the beginning using a procedure Looping your code back Using a while loop to create a menu driven interface in Python - Duration:
Pythonic Code: Best Practices to Make Your Python More Readable, If you're someone who has spent some time writing Pythonic code, you will have come across the best practices. One Statement of Code per Line searching for items in the collection; you do not have duplicate items as most of the Python packages have/will stop releasing updates for Python 2.x. Guys please help this channel to reach 20,000 subscribers. I'll keep uploading quality content for you. Python is easy programming language to learn and anyone can learn it, and these tutorials