Reading and Writing Files

  • We open files using the built-in open function. We need to tell the function if the file is to be used for reading, writing, or appending with the r, w, and a flags.

  • All the test files for the course are located at https://ki-data.mit.edu/bcc/teaching/IntroToPython.tgz.

  • If you are on our cluster, you can copy them all to the current directory by typing:

cp /net/bmc-pub15/data/bmc/public/BCC/external/teaching/IntroToPython/* ./

Examples

  • Reading file seq.txt

In [1]: fin=open('seq.txt')

In [2]: fin=open('/net/rowley/ifs/data/bcc/dropbox/teaching_python/seq.txt')

In [3]: fin=open('seq.txt','r')
  • Writing to file seq2.txt

In [1]: Aa="GLECDGRTNLCCRQQFF"
In [2]: fo=open('seq2.txt','w')
In [3]: fo.write(Aa)
In [4]: fo.close()
Out[4]: <function close>
In [5]: less seq2.txt
GLECDGRTNLCCRQQFF

*no need to remember to close the file handler if using "with" statement 
In [1]: with open('seq2.txt','w') as fo:
   ...:     fo.write("ABC")
   ...:     
In [2]: less seq2.txt
ABC

Note: writing to a file will delete the existing content of the file
  • Appending to file seq2.txt

  • Reading files with read() and readlines()

  • We can read in a file using our Python script, process it, and output the results to an output file

    • Let's read in file seq.txt

    • find the palindrome sequences using our python script

    • Then output the palindrome sequences to file palindrome.txt

  • Let's do an exercise by writing a Python script to say hello to the class

    • First read in file class_list as a list

    • Then output our greetings to file greetings

  • To avoid changing scripts, we can use arguments to read input files and to write output files

    • ./hello_class2.py class_list greetings_again

  • Input another class list to hello_class2.py will output greetings to another class

    • ./hello_class2.py future_class_list greetings_to_future_class

Last updated

Was this helpful?