Reading files. A txt file can be considered as a sequence of lines, you can find an example of an email. This can be considered as a file, we can save it onto our hard drive. Before we can read the contents of the file, we have to tell Python which file we want to work with. And let us know what changes we want to make. We do this with the open command.
The open function returns as the file handle, and variable used to perform operations on the file. Similar to file open after word processing program word. Handle is equal to open file name mode allows us to acquire a handle used to handle files. file name is a character string. The processing mode is optional, and should be our if we intend to read the file. And w if we intend to write to the file.
Through the handle. You choose what you want the program to do to the file. You can open it Buy to it, read from it or close it. When a file is not found, it will give you an IO error stating the file was not found. This can happen if you input the wrong path for the file no longer exists. We use a special character named new line to indicate when a line stops.
In strength, we write backslash and new line represents a character not to a text contains new lines at the end of the line. How to count file lines, open a file to read only use a further to read each line. Count the lines and print the number of lines you can remove the blanks on the right side of the string by using the restrict function in the string library. The line spacing is considered to be a blank and therefore it is deleted. In this example, we search for the from element This will tell us who sent the email. We can conventionally skip a line using the continue declaration.
Here, we skip the line which contains where the email was sent from. In this example, we find how many times the sentence starts with object. If the file cannot be opened, we will catch this in the try except clause.