 <p><code>os.listdir()</code> returns a list of strings much like the terminal command <code>ls</code>. It lists the names of the files, but it does not include the name of the directory. You need to add that yourself with <code>os.path.join()</code>:</p> <pre><code>def replace(directory, oldData, newData): for file in os.listdir(directory): file = os.path.join(directory, file) f = open(file,'r') filedata = f.read() newdata = filedata.replace(oldData,newData) f = open(file, 'w') f.write(newdata) f.close() </code></pre> <p>I would not recommend <code>file</code> as a variable name, however, because it conflicts with the built-in type. Also, it is recommended to use a <code>with</code> block when dealing with files. The following is my version:</p> <pre><code>def replace(directory, oldData, newData): for filename in os.listdir(directory): filename = os.path.join(directory, filename) with open(filename) as open_file: filedata = open_file.read() newfiledata = filedata.replace(oldData, newData) with open(filename, 'w') as write_file: f.write(newfiledata) </code></pre>