File Operations

From Training Material
Jump to navigation Jump to search


Opening files for reading

Text files can be accessed using the open() function. It returns an open file from which its contents can be extracted as a string.

f = open('my_file.txt')
text = f.read()

Opening files for writing

Writing text to files is very similar. The only difference is the 'w' parameter.

f = open('my_file.txt','w')
f.write(text)

Appending to files

It is possible to add text to an existing file, too.

f = open('my_file.txt','a')
f.write(text)

Closing files

Closing files in Python is not mandatory.

f.close()

Tips for reading files:

An open file behaves like a list of strings. Thus, it is possible to read it line by line without using s.split('\n'):

for line in open('my_file.txt'):
name = line[:10].strip()
print name

Tips for writing files:

Analogously, if you have data as a list of strings, it can be written to a file as a one-liner. You should remember to have linebreaks:

lines = ['first line\n',
'second line\n']
open('my_file.txt','w').writelines(lines)

Take care of IOErrors

You should keep in the back of your head that opening a non-existing file for reading causes an IOError. Eventually, a try.. except clause is useful, then (but not always).

Writing directory names in Python

When opening files, you can also use full or relative directory names. However, you must replace the backslash '\' by a double backslash '\\' (because '\' is also used for '\n' and '\t').

f = open('..\\my_file.txt')
f = open('C:\\python\\my_file.txt')

Managing directories

With the os module, you can change to a different directory:

import os
os.chdir(''..\\python'')

You can also get a list with all files:

os.listdir(''..\\python'')

The third most important function is for checking whether a file exists:

print os.access('my_file.txt')

The CSV module

An open file behaves like a list of strings. Thus, it is possible to read it line by line without using

import csv
reader = csv.reader(open('my_file.csv'))
for row in reader:
print row

Similarly, tables can be written to files:

writer = csv.writer(open('my_file.csv','w'))
writer.writerow(table)

Options of CSV file readers/writers

Both CSV readers and writers can handle a lot of different formats. Options you can change include:

  • delimiter: the symbol separating columns.
  • quotechar: the symbol used to quote strings.
  • lineterminator: the symbol at the end of lines.
reader = csv.reader(open('my_file.csv'),
delimiter='\t', quotechar='”')