Login using Social Account
     Continue with GoogleLogin using your credentials
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()
file_read_func
that takes the path of the file as an argument (assume it as str
format). -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)-
65
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
Note - Having trouble with the assessment engine? Follow the steps listed here
Loading comments...