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.
In [1]:
cat example.txt
In [2]:
my_file = open("example.txt")
for line in my_file:
print line.strip()
my_file.close()
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
In [5]:
%%writefile?
In [6]:
%%writefile ipython-writefile-example.txt
I wrote this file.
I used `writefile` in the 12-Files notebook!
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]:
In [ ]: