0

I've got two examples of code, that are supposed to perform the same thing (process text files and save the result to an outfile). However, this one doesn't work for me:

with codecs.open('outfile.txt', 'w', 'utf-8') as outfile:
    for f in os.listdir(my_files):
        outfile.write(some_function(codecs.open(f, 'r', 'utf-8')))
        outfile.write('\n')

Whereas this works perfectly:

outfile = open('outfile.txt', 'w')
for f in os.listdir(my_files)
    with open(f) as f_:
        text = f_.read().decode('utf-8')
    text = some_function(text)
    outfile.write(text.encode('utf-8'))
    outfile.write('\n')

Am I doing something wrong with python codecs? Thank you!

1
  • Maybe provide your error? :) Commented Jun 23, 2017 at 12:56

1 Answer 1

2

This line...

outfile.write(some_function(codecs.open(f, 'r', 'utf-8')))

...opens a file object without passing any text. You'll want to tack on a read() to get it working, like this: codecs.open(f, 'r', 'utf-8').read()

Sign up to request clarification or add additional context in comments.

3 Comments

Oh my god, that totally solved the problem! Thank you so much :)
now I feel so stupid for asking such questions :) I literally spent an hour trying to understand what's wrong
@DariaSmirnova Cheers. It happens to us all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.