Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are <em>two</em> big problems with your code:</p> <p>First, <code>line.replace</code> won't do anything to <code>line</code> itself. As the docs say, it will:</p> <blockquote> <p>Return a copy of the string with all occurrences of substring old replaced by new…</p> </blockquote> <p>But you're not storing that new string, or doing anything else with it.</p> <p>Second, you never write anything to <code>converted</code>.</p> <p>To fix both at once:</p> <pre><code>for line in file: if '0' in line: converted.write(line.replace('0', 'ZERO')) elif '1' in line: converted.write(line.replace('1', 'ZERO')) else: return </code></pre> <p>However, you also have a number of small problems. You <code>return</code> the first time you find a line with no <code>0</code>s or <code>1</code>s. If a line has both <code>0</code>s and <code>1</code>s, you will only replace the <code>0</code>s. You never <code>close</code> the file, which means the file may never get flushed to disk, and could end up empty or incomplete. So, let's fix all of those problems as well:</p> <pre><code>with open(fileName, "r") as file, open('converted.txt', 'w') as converted: for line in file: line = line.replace("0", "ZERO") line = line.replace("1", "ONE") converted.write(line) </code></pre> <p>It's perfectly safe to <code>replace</code> all the 0s even if there aren't any—it just won't do anything. (If you were trying to optimize things by skipping the expensive work if there was no work to do, the <code>"0" in line</code> takes just as long as the <code>replace</code> when there's nothing to do, so you've actually pessimized things… which is a good lesson to learn early in your programming career.) This means you don't need the <code>if</code> statements at all, you don't have to fix the way you've chained them up, and you don't have the problem with the <code>return</code> in the <code>else</code>.</p> <p>And the <code>with</code> statement automatically calls <code>close</code> on both <code>file</code> and <code>converted</code> for you as soon as you leave it (even if you leave early because of, say, an unexpected exception).</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