LPTHW - EX17 - Study Drills - Don't bother reading this


I have typed in the code and run it and everything works fine. I have tried to find a way to reduce the code in lines 9 & 10 to one line, but could not figure it out. I can see that we can reduce the code by eliminating line 21 and probably line 6 that just tells us what the code is going to do, but doesn’t actually do anything other than print the message about what is going to happen.

I noticed that we cannot have a [new_file.txt] in existence before we start the script or it will produce a “TRUE” rather than FALSE evaluation in line 14 when we call exists(to_file)

I understand that the text in the command line that says:
echo “This is a test file.” > test.txt will do two tasks. It will create a file named “test.txt” and fill it with the follow text: “This is a test file.”

I also understand that “cat test.txt” will print out the content of the file ‘test.txt’

I understand that in the command line [ex17.py], [test.txt], [new_file.txt] are the variables for argv which was imported from the sys module.

Where does the code tell Python to copy the contents of the file “test.txt” to the file “new_file.txt”

I believe that [test.txt] --> becomes [from_file] —> becomes [out_file]
I believe that [new_file.txt] —> becomes [to_file] --> becomes [in_file]

There are four lines of code that confuse me:
in_file = open(from_file)
indata = in_file.read()
out_file = open(to_file, ‘w’)

I believe that the value of the variable [indata] are the contents of the original test.txt file or “This is a test file.”
I believe that the code:
out_file.write(indata) is writing the contents of the original test.txt to the variable [out_file]. Is this where the copy task being done???

What is being assigned to the variable [out_file] in the code, "open(to_file, ‘w’). I know that ‘w’ means “write” and that ‘r’ means “read”. What happens in open(filename, ‘w’).

This is how to open a file
file_object = open( filename, ‘mode’)
This seems to be equivalent to the code:
out_file = open(to_file, ‘w’)

I guess I feel like there must be a piece of code that reads and holds a copy of the content in test.txt and places that copy into new_file.txt. I feel like we are going in circles here. Why do we need to create all these multiple variables. The code seems unnecessarily complex, but I can’t figure out a better way.


Yes, you are pretty close, but I also use a trick. You can join lines of code with ;