In the web application we built in the last chapter, we will try to find the answer's to these question in the present chapter
- How many request have been responded to?
- What's the most common list of letters?
- Which IP address are the request coming from?
- Which browser is being used the most?
- The most easy way to store data is in text file.
- Python comes with built-in support for open, process, close
- open : Open a file
- process : process its data in some way
- close : close the file when finished.
todos = open('todo.txt', 'a')- It open a file name
todo.txt. - The file is opened in
a, i.e. append mode. todosis the file stream.
- It open a file name
print("text", file=todos)+print()takes an argumentfile, which redirect the text to the file.todos.close(): The open files stream should be closed, else we can loose the data.
- To read a file we can
open()the file in default mode, which is thereadmode.
tasks = open('todo.txt')
for chore in tasks:
print(chore)
tasks.close()- In the above code
todo.txtis opened in read mode. - The python
forloop when used with a file stream is intelligent enough to read a line of data from the file each time the loop operates. - There is already new line at the end of each line in the file, in addition
print()adds extra line, we can passend=""to stop that extra line. - Modes of file open :
'r': Open a file for reading.'w': Open the file for writing. It empty the file content if present.'a': Open the file for append. The old content of the file is preserved.'x': Open a new file, throws error if file exist.
'b': The above modes of file open is for textual data, if the file has binary data, append the above modes with'b', like'ab'ora+b.
withstatement is preferred in place of theopen, process andclosestages.
with open('todos.txt') as task:
for chore in tasks:
print(chore, end="")withstatement is smart enough to remember to callcloseon our behalf.withstatement conforms to a coding convention called context management protocol.withstatement manages the context within the block it runs..read(): reads the complete content of the file and loads into memory.escape():Flaskprovides a function calledescapewhich escape's based on HTML template.
'|'.join("hello", "brother"): joins the two words using the|as the separator..split('separator'): splits a string to list based on the separator supplied.