Enrollments started for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 5 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
The data on our systems is stored in the files. Python helps us handle files as well.
For reading or writing to a file, we must open the file.
f = open("file_name.txt")
If the file opens successfully, the operating system returns us a file handle
. The file handle
is not the actual data contained in the file, but instead, it is a "handle" that we can use to read the data. We are provided with a handle
if the requested file exists and we have the proper permissions to read the file.
If there is no file with the name we mentioned, open
will fail with a traceback and we will not get a handle to access the contents of the file.
The file should be stored in the same folder that you are in when you start Python. In that case, i.e. if there is any chance of file not being present, we can try
and except
to deal with the exception.
A text file is just a sequence of lines or str
in Python. Each line is separated by a "\n"
.
In Python, we represent the newline character as a backslash-n
in string constants. When we try printing the "\n"
in the string, it breaks the string into different lines.
print("cloud\nx\nlab")
It will print,
cloud
x
lab
So, when we are reading lines, we need to imagine that there is a special invisible character '\n'
called the newline at the end of each line that marks the end of the line.
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
No hints are availble for this assesment
Answer is not availble for this assesment
Loading comments...