Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instead of providing you with some code which you will simply copy-paste without understanding, I'd like to walk you through the solution so that you will be able to write it yourself, and more importantly gain enough knowledge to be able to do it alone next time.</p> <p>The code which does what you need is made up of three main parts:</p> <ol> <li>Getting a list of all filenames you need to iterate</li> <li>For each file, extract the information you need to generate a new name for the file</li> <li>Rename the file from its old name to the new one you just generated</li> </ol> <h3>Getting a list of filenames</h3> <p>This is best achieved with the <a href="http://docs.python.org/library/glob.html" rel="nofollow"><strong>glob</strong></a> module. This module allows you to specify shell-like wildcards and it will expand them. This means that in order to get a list of <code>.txt</code> file in a given directory, you will need to call the function <code>glob.iglob("/path/to/directory/*.txt")</code> and iterate over its result (<code>for filename in ...:</code>).</p> <h3>Generate new name</h3> <p>Once we have our filename, we need to <code>open()</code> it, read its contents using <code>read()</code> and store it in a variable where we can search for what we need. That would look something like this:</p> <pre><code>with open(filename) as f: contents = f.read() </code></pre> <p>Now that we have the contents, we need to look for the unique phrase. This can be done using <a href="http://docs.python.org/library/re.html" rel="nofollow"><strong>regular expressions</strong></a>. Store the new filename you want in a variable, say <code>newfilename</code>.</p> <h3>Rename</h3> <p>Now that we have both the old and the new filenames, we need to simply rename the file, and that is done using <code>os.rename(filename, newfilename)</code>.</p> <p>If you want to move the files to a different directory, use <code>os.rename(filename, os.path.join("/path/to/new/dir", newfilename)</code>. Note that we need <code>os.path.join</code> here to construct the new path for the file using a directory path and <code>newfilename</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload