Study drill 6 and 7 exercise 15


#1

STUDY DRILL 6:

When I open python3.6 on terminal, and type in line 3 ie script, filename = argv -->; not enough variables to unpack.

Now if I don’t type in the first two lines ie lines 1 and 3, and straight type txt = open(ex15_sample.txt) I get “name ex15_sample is not defined.”

Because of these errors, I cannot proceed with reading the files through python shell on terminal.

STUDY DRILL 7:

In the script on atom, after print(txt.read()) I type txt1 = close(filename) and then I run it on terminal --> it says “name close is not defined.” I don’t understand why I get this error when we did not have to define open so why do we have to define close?


#2

I’m a C student, not Python. But I looked up the close function. This page has simple code examples: python file handling.

Two things I’m spotting in the example code is that they don’t bother handling any return value from the close function, and it’s run from the file object rather than as an individual function. Does this apply in your case?

fh = open("hello.txt", "r")
print fh.read() 
fh.close()

#3

Study Drill 6:

If you want to open a file from within the python shell you don’t need argv. argv you only need if you want to run a script and give some parameter to it.

So, go to your terminal an open up a python shell:

$ python3.6

Then, inside the Python shell you can open the file ex15_sample.txt directly:

open("ex15_sample.txt")

You see something like this:

>>> open("ex15_sample.txt")
<_io.TextIOWrapper name='ex15_sample.txt' mode='r' encoding='UTF-8'>

Study Drill 7:

After you opened the file you can do some work with it. To do that you need to assign your open function to a variable. So instead of open("ex15_sample.txt") you have to do something like this filename = open("ex15_sample.txt")
Whit that you have a variable you can work with.
To read the content of the file open("ex15_sample.txt") you have to write:

filename.read()

to close it you have to write:

filename.close()

The whole code:

$ python3.6
Python 3.6.7 (default, Oct 25 2018, 09:16:13) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> filename = open("ex15_sample.txt")
>>> filename.read()
'This is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.\n'
>>> filename.close()
>>> 

The difference between open() and close() is that open() is a function and close() is a method. The first one you call first, like open("sample.txt") the second one you call after, like filename.close(). You don’t have to bother with the difference, you will learn later what it means, the only important thing for you for now is to remember that you have to call them differently.


Built in function syntax
#4

Yep, what @DidierCH said is right. @lee8oi made a pretty good guess for someone not doing python. Let me know if you need help still on this.