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: "cat" here is an ipython "line magic." It's not part of regular python. It displays the contents of a file.


In [1]:
cat example.txt


This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.

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


This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.

Writing to a file


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

In [4]:
cat example2.txt


bears
beets
Battlestar Galactica

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 [5]:
%%writefile?

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


Writing ipython-writefile-example.txt

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 [7]:
# Store the genotypes from genos.txt in this list
genos_from_file = []

Check your work:


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


Out[8]:
False

In [ ]: