Halloween Sale: Flat 70% + Addl. 25% Off + 30 Days Extra Lab on all Courses | Use Coupon HS25 in Checkout | Offer Expires InEnroll Now
We can use a
for loop to read a file's data using it's handle,
f = open("/cxldata/python_sample_file")
You also need to close the handle once it is of no use by
So there is a better way to read the file using
with so that you do not have to worry about closing the handle. In this case, the handle is only valid only within the block of
with open("/cxldata/python_sample_file") as f: s = "" for line in f: print(line) s = s + line print(s)
We need to place the path of the file inside the brackets and the file handle is stored in
f. Try it in the notebook and see the results. It should print each line in the file and then print all the all lines as concatenated one
We can also read the whole file into one string using the
read method on the file handle.
content = f.read()
file_read_functhat takes the path of the file as an argument (assume it as
-1, else return the sum of the lengths of all words in the file.
"\n"which is the newline character.
Sample Input file -
This is a sample file for testing for Python course for learners in CloudxLab.
Sample output (which is the sum of the length of all the words)-
No hints are availble for this assesment
Answer is not availble for this assesment
Note - Having trouble with the assessment engine? Follow the steps listed here