opening several txt files using while loop
<p>I have some txt files that their names have the following pattern: </p>

<pre><code>arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt
</code></pre>

<p>I know  that we can write a program using <code>for loop</code> to open the files one by one, if we now the total numbers of files. I want to know is it possible to use <code>While loop</code> without counting the number files to open them ?  </p>

<p>It is definitely possible to use a while loop assuming that the files are numbered in sequential order:</p>

<pre><code>i = 0
while True:
    i += 1
    filename = 'arc.%d.txt' % i
    try:
        with open(filename, 'r') as file_handle:
            ...
    except IOError:
        break
</code></pre>

<p>Though this becomes pretty ugly with all the nesting.  You're probably better off getting the list of filenames using something like <a href="https://docs.python.org/2/library/glob.html#glob.glob" rel="nofollow"><code>glob.glob</code></a>.</p>

<pre><code>from glob import glob
filenames = glob('arc.*.txt')
for filename in filenames:
    with open(filename) as file_handle:
        ...
</code></pre>

<p>There are some race conditions associated with this second approach -- If the file somehow gets deleted between when <code>glob</code> found it and when it actually is time to process the file then your program could have a bad day.</p>

python for-loop text while-loop