Updated: Jan 28
We use open() method to open a file, first parameter is file_name, and second parameter is mode. The default value of the second parameter is 'r', which is 'read' mode to read text file, for reading binary files, we use 'rb'
following samples are using a test file in the current working directory file_name: test.txt 1) This is a test file 2) second line 3) third line
read () method will read whole file; it's not recommended for the large files.
close () method will close the file object, if you forget to close, you will end up with memory leak.
The recommended way to open a file, is to use the context manager, python provides 'with' statement to use the context manager, it will take responsibility to close the file automatically, even some exception is thrown.
The open() function returns a file object. A python file object has 3 reading methods, which gives us enough flexibility to get the contents:
read(): read the entire file and save the contents to a python string object. Sometimes a file is larger than the available memory, in order to be safe, we can use the parameter 'n' to read 'n' characters each time: read(n). The default value of n is -1, which means read the whole file.
readlines() is also to read entire file, but it will automatically analyses the file contents and convert them into a list of lines.
readline() reads only one line of the file contents each time. so, programmatically we are iterating through each line.
Reading a chunk of memory, while working from large files...
Reading file pointer current position in the file:
Move the Pointer in a File
The file object has a seek(offset, whence=0) method which is used to move the file pointer in the file.
offset: indicates how many characters.
0 - beginning from the file
1 - from the current position
2 - end of the file
Seek() function with negative offset only works when file is opened in binary mode.
reading data from one file, and writing to another file:
copying a 'jpeg' file
copying a chunk of memory from a 'jpeg' file