flush()method can be used to immediately write to the file. The
close()method internally calls the
flush()method, thus, in most of the cases, it is enough to just call the
writemethod doesn't add a new line character at the end of each operation. To understand it better, open this file in a text editor.
list.strip()would be the elements of the list. The second argument is the for loop, the third argument is optional, you can have an
bstands for binary, along with
b, we can use any of r/w/a.
Note: One essential part of working with files is removing the
\nor adding it when it is required.
read()Takes an argument as number of bytes to be read.
f.read(1), the pointer moves to 1. If you do
f.read(1)again, the pointer would return the 2nd character of the file and not the first one.
Note: This is a session for the Interpreter.
seekfunction to reset the pointer at any position of your choice. Let's say that you want to re-read the file again
readline()Returns the current line that the pointer is located.
f.seek(0)and reading the lines again, you'll get the same output as above.
readlines()Returns all the lines of the file as a list.
f.seek(0)to reset the pointer.
write()Writes the string argument which you pass on the pointer. We need to be careful of the pointer, otherwise writing to the file can be dangerous. You are responsible for adding the "\n" character if you want to a new line, by default it'll write at the position the pointer is currentl
writelines()If you want to write a list to a file, you'll use writelines. Even here you are responsible for adding \n wherever you feel necessary.