Foundations of Python

You are currently auditing this course.
102 / 134

Reading Files

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 f.close().

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,

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()
INSTRUCTIONS
  • Define a function with the name as file_read_func that takes the path of the file as an argument (assume it as str format).
  • Your code should check whether the file exists or not with the given path.
  • If there is no file at the given path, return -1, else return the sum of the lengths of all words in the file.
  • Please note that your code should not count "\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)-

65


Loading comments...