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 [ ]:
less example.txt
In [ ]:
my_file = open("example.txt")
for line in my_file:
print line.strip()
my_file.close()
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
In [ ]:
%%writefile?
In [ ]:
%%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 [ ]:
# Store the genotypes from genos.txt in this list
genos_from_file = []
In [ ]:
genos_from_file[:15] == [2, 2, 1, 1, 0, 0, 2, 2, 2, 0, 'NA', 1, 0, 0, 2]