Video Pending

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

17: More Files

Now let's do a few more things with files. We'll write a Python script to copy one file to another. It'll be very short but will give you ideas about other things you can do with files.

from os.path import exists

from_file = "test.txt"
to_file = "new_test.txt"

print(f"Copying from {from_file} to {to_file}")

# we could do these two on one line, how?
in_file = open(from_file)
indata =

print(f"The input file is {len(indata)} bytes long")

print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")

out_file = open(to_file, 'w')

print("Alright, all done.")


You should immediately notice that we import another handy command named exists. This returns True if a file exists, based on its name in a string as an argument. It returns False if not. We'll be using this function in the second half of this book to do lots of things, but right now you should see how you can import it.

Using import is a way to get tons of free code other better (well, usually) programmers have written so you do not have to write it.

Previous Lesson Back to Module

Register for Learn Python the Hard Way, 5th Edition (2023-2024)

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.