title: Reading variable values from an external file in Python
body: <p>The Objective: Bulk copy selected files from one directory to another directory on the same remote server by calling each filename into a Python script as a variable from an external file containing a list of the filenames to be copied.</p>
  <p>The Problem: there are well over 1000 files I need to copy, so pasting the filenames into a list or dict within the script itself doesn't seem to make sense. I can read and <em>print</em> the filenames from an external file just fine.</p>
  <pre><code>def main():
      f = open(&quot;file-list.txt&quot;, &quot;r&quot;)
      if f.mode == 'r':
          flist = f.readlines()
          for x in flist:
              print(x.rstrip('\n'))
              
  if __name__ == &quot;__main__&quot;:
      main()
      
  Output:
  file-1.txt
  file-2.txt
  </code></pre>
  <p>However, in order to copy the files in sequence, I need to loop through file-list.txt and have those filenames called as variables into an shutil.copy statement; but this is throwing an invalid syntax error.</p>
  <pre><code>import os
  from os import path
  import shutil
  
  def main():
      f = open(&quot;file-list.txt&quot;, &quot;r&quot;)
      if f.mode == 'r':
          flist = f.readlines()
          for x in flist:
              shutil.copy(r&quot;folder_1/&quot;%s&quot;,&quot;folder_2/&quot;%s&quot;) % x    
              
  if __name__ == &quot;__main__&quot;:
      main()
  
  Output:
  File &quot;&lt;ipython-input-3-223c95b85768&gt;&quot;, line 10
      shutil.copy(r&quot;folder_1/&quot;%s&quot;,&quot;folder_2/&quot;%s&quot;) % x
                                  ^
  SyntaxError: invalid syntax
  </code></pre>
  <p>I feel like I'm missing something basic, so any tips or advice toward a solution would be welcome!</p>
  <p><strong>Solution</strong> - with thanks to all commenters!</p>
  <pre><code>import shutil
  
  def main():
      cleanlist =[]
      f = open(&quot;file-list.txt&quot;, &quot;r&quot;)
      if f.mode == 'r':
          flist = f.readlines()
          for element in flist:
              cleanlist.append(element.rstrip())
          for x in cleanlist:
              shutil.copy(f&quot;folder_1/{x}&quot;,f&quot;folder_2/{x}&quot;)    
              
  if __name__ == &quot;__main__&quot;:
      main()
  </code></pre>