Write a function that reads a file, uppercases its content, and writes the result to a second file.
uppercase_file(in_path, out_path)
Read the file at in_path, write .upper() of its content to out_path, and return "done".
Given in_path containing "hello world", after calling uppercase_file(in_path, out_path), out_path contains "HELLO WORLD".
def uppercase_file(in_path, out_path):
with open(in_path) as f:
content = f.read()
with open(out_path, "w") as f:
f.write(content.upper())
return "done"
This is the "read-then-transform-then-write" shape from the lesson, applied directly: one with block reads in_path fully into content (and closes it), then a second, separate with block opens out_path in "w" mode and writes the transformed (.upper()'d) content to it.
Using two separate with blocks — rather than trying to hold both files open at once — keeps things simple: by the time you're writing, you already have everything you need from the input file sitting in the content variable, and the input file itself is already closed.
"w" mode is important here: it creates out_path if it doesn't already exist, and if it does exist, "w" mode erases whatever was there first — exactly the behavior you want when producing a fresh output file.
def uppercase_file(in_path, out_path):
with open(in_path) as f:
content = f.read()
with open(out_path, "w") as f:
f.write(content.upper())
return "done"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.