Python Reading And Writing Files

Python Reading And Writing Files

File reading and File writing is widely used concept in python because, As we (i.e humans) are lazy we do not remember all the information so we invented the computers(i.e storage devices) to store the information. where will computers store the information? Computer always stores the information in files. Hence, As we programmers we have to learn python file reading and writing so that we can play with files.

Python File Reading

In python we have a keyword named "open" by using that keyword we open files and read contents of it. Let's see a code example to read a simple text file.

file_location = '/home/ubuntu/sample.txt'
open_mode = 'r'
file = open(file_location, open_mode)
contents = file.read()
print(contents)
file.close()
# output:
# Hello World
# Hello Python
  • python keyword "open" takes two parameters to read the file. First parameter is location of the file(i.e full path of the file where the file resides in the operating system) and second parameter is opening mode type.
  • Based on the mode type file will be open for reading or writing.
  • Types of file modes in python
Mode Description
'r' Opens file for reading
'w' Opens file for writing. It creates a new file if file does not exist or truncates the file if exists.
'x' Opens file for exclusive creation. If the file already exists, the operation fails.
'a' Opens file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Opens file in text mode.
'b' Opens file in binary mode.
'+' Opens file for updating both reading and writing
  • Choose the file opening mode based on the requirement whether you want to open it for reading or writing.
  • Opening the file for reading is faster than writing or appending.
  • "read" is file method which is used to read the contents of the file.
  • It's always recommended to close the file after opening it. Because whenever we opens the file the operating system loads the file contents into the memory. When we close the file then that occupied memory will be freed.

Python File Writing

file_location = '/home/ubuntu/sample.txt'
open_mode = 'w'
file = open(file_location, open_mode)
file.write("Hello Google\n")
file.write("Hello Yahoo")
file.close()
# output:
# Hello World
# Hello Python
* In above code we have used the file open mode "w" to write the contents into the file. * We have used the file method "write" which is used to write the contents into the file. * It's always recommended to close the file after our usage.

Available Python File Methods

Method Description
close() It closes the file if opened (no effect otherwise)
detach() Separates the underlying binary buffer from the TextIOBase and return it.
fileno() It returns descriptor of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can nbe read from.
readline(n=-1) Read and return one line from the file. Reads in at most nbytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from(start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write string s to the file and return the number of characters written.
writelines(lines) Write a list of lines to the file.

Pythonic way to open and close the file

  • We generally opens a file and do some operations with it and then closes it. Whe doing operations if we get any error then the file remains opened. The file uses memory for no use. So, We should always close the file though we get errors. We can achieve it using "try ... finally" in python.
  • Let's see an example code
file_location = '/home/ubuntu/sample.txt'
try:
   file = open(file_location, 'a+')
   # do some operations
finally:
   file.close()
  • Above example can be simplified as below
file_location = '/home/ubuntu/sample.txt'
with open(file_location, 'a+') as file:
   # do some operations

Reference: https://docs.python.org/dev/library/io.html