Python 3x Pandas Django

File Handling


Python has several functions for creating, reading, updating, and deleting files.

Reading and Writing Files

The key function for working with files is the open() function.

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

f = open('workfile', 'w')

a. The first argument is a string containing the filename.

b. The second argument is another string containing a few characters describing the way in which the file will be used

"r"  - Read   - Default value
              - Opens a file for reading, error if the file does not exist
"a"  - Append - Opens a file for appending, creates the file if it does not exist
"w"  - Write  - Opens a file for writing, creates the file if it does not exist
              - (or) an existing file with the same name will be erased
"x"  - Create - Creates the specified file, returns an error if the file exists
"+" - Read & Write - Opens the file for both reading and writing

"t" -	Default value - Opens in text mode.
"b" -	Opens in binary mode

Syntax

f = open('workfile')        # Default Mode: 'r' - read  & 't' - text
f = open('workfile', 'at')  # Mode: Append & Text
f = open('workfile', 'wt')  # Mode: Write & Text
f = open('workfile', 'xt')  # Mode: create & Text
f = open('workfile', 'rb')  # Mode: read & binary

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('workfile') as f:
     read_data = f.read()

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.

read()

f = open('workfile', 'r')
f.read()  #Output: 'This is the first and last line of the file..\n'
f.read()  #Output: ''
f.close()

f.read() - 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 ('')

readline()

f = open('workfile', 'r')
f.readline()  #Output: 'This is the first line of the file..\n'
f.readline()  #Output: 'This is the second and last line of the file..\n'
f.readline()  #Output: ''
f.close()

1. f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string.

2. f.readline() returns an empty string when it reaches the end of the file.

3. '\n' is represented a blank line.

The best way for reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

for line in f:
   print(line, end='')
f.close()

Output:

This is the first line of the file.
this is the Second line of the file

list(f) or f.readlines() - read all the lines of a file in a list data structure

f.read(5) - you can also specify how many characters you want to return

write()

f.write("string") writes the contents of string to the file, returning the number of characters written

with open('C:\\Users\\user\\workfile.txt', 'w') as f:
      no_of_chars  = f.write('This is first line in this new file\n')
      print(no_of_chars)            #Output: 15

with open('C:\\Users\\user\\workfile.txt', 'a') as f:
      no_of_chars  = f.write('This is a second line appending into this file\n')
      print(no_of_chars)            #Output: 47

Output:

C:\\Users\\user\\workfile.txt

This is first line in this new file
This is a second line appending into this file

Delete a File

To delete a file, we have to use os python package function os.remove()

import os
os.remove("C:\\Users\\user\\demofile.txt")

Check if this file exists, and then delete it (To avoid getting an python error FileNotFoundError)

import os
if os.path.exists("C:\\Users\\user\\workfile.txt"):
  os.remove("C:\\Users\\user\\workfile.txt")
else:
  print("This file does not exist") in  #Output: This file does not exist

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!