Python: File operations

Materials by: John Blischak and other Software Carpentry instructors (Joshua R. Smith, Milad Fatenejad, Katy Huff, Tommy Guy and many more)

In this lesson we will cover how to read and write files.

Reading from a file

Note: "less" here is an ipython "line magic." It's not part of regular python. It displays the contents of a file.


In [ ]:
less example.txt

In [ ]:
my_file = open("example.txt")
for line in my_file:
    print line.strip()
my_file.close()

Writing to a file


In [ ]:
new_file = open("example2.txt", "w")
dwight = ['bears', 'beets', 'Battlestar Galactica']
for i in dwight:
    new_file.write(i + '\n')
new_file.close()

In [ ]:
less example2.txt

Creating a file with magic

IPython provides a simple mechanism to define a quick file kind of like a text editor. It will end up in the same directory where you're working with the notebook.


In [ ]:
%%writefile?

In [ ]:
%%writefile ipython-writefile-example.txt
I wrote this file.
I used `writefile` in the 12-Files notebook!

More genetics examples

The file genos.txt has a column of genotypes. Read in the data and convert the genotypes as above. Hint: You'll need to use the built-in string method strip to remove the new-line characters (See the example of reading in a file above. We will cover string methods in the next section).


In [ ]:
# Store the genotypes from genos.txt in this list
genos_from_file = []
Check your work:

In [ ]:
genos_from_file[:15] == [2, 2, 1, 1, 0, 0, 2, 2, 2, 0, 'NA', 1, 0, 0, 2]