Reading and Writing Files:
open() returns a file object and is most used with two arguments: open(filename, mode).
f = open(‘logfile’, ‘w’)
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be ‘r’ when the file will only be read, ‘w’ for only writing (an existing file with the same name will be erased), and ‘a’ opens the file for appending; any data written to the file is automatically added to the end. ‘r+’ opens the file for both reading and writing. The mode argument is optional; ‘r’ will be assumed if it’s omitted.
with keyword when dealing with file objects:
It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:
with open(‘logfile’) as f:
… read_data = f.read()
Methods of File Objects:
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string (‘’).
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by ‘\n’, a string containing only a single newline.
f.readline()
‘This is the first line of the file.\n’
f.readline()
‘Second line of the file\n’
f.readline()
‘’
If you want to read all the lines of a file in a list, you can also use list(f) or f.readlines().
f.write(string) writes the contents of string to the file, returning the number of characters written.
f.write(‘This is a test\n’)
15

Leave a comment