File input and output Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble Notes from 2009: Sample problem.

Slides:



Advertisements
Similar presentations
For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
Advertisements

While loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
CHAPTER 11 FILE INPUT & OUTPUT Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Computer Science 111 Fundamentals of Programming I Files.
File input and output if-then-else Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Last Week Looping though lists Looping using range While loops.
Why use Files? Your Python Program External File (secondary storage) Write to file (Save) Read from file (Load) …so we can have access to ‘stored’ data.
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Introduction to C++ - How C++ Evolved Most popular languages currently: COBOL, Fortran, C, C++, Java (script) C was developed in 1970s at AT&T (Richie)
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
Introduction to Python Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Numbers, lists and tuples Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
File I/O Michael Ernst UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
File I/O Ruth Anderson UW CSE 160 Spring File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Last Week Lists List methods Nested Lists Looping through lists using for loops.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
File input and output and conditionals Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
File I/O Ruth Anderson UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Lakshit Dhanda. Output Formatting Python has ways to convert any value to a string. 2 Methods repr() – meant to generate representations of values read.
Kanel Nang.  Two methods of formatting output ◦ Standard string slicing and concatenation operations ◦ str.format() method ie. >>> a = “The sum of 1.
Python focus – files The open keyword returns a file object Opening a file myFile = open('C:\file.txt', arg) Optional argument The second argument controls.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files.
CMSC201 Computer Science I for Majors Lecture 10 – File I/O
EECS 183 Discussion #9: It’s time to “Git” Python! November 22nd, 2016
For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
CompSci 6 Introduction to Computer Science
File Writing Upsorn Praphamontripong CS 1110
Introduction to Python
(optional - but then again, all of these are optional)
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
(optional - but then again, all of these are optional)‏
Ruth Anderson UW CSE 160 Winter 2016
Introduction to Python
Numbers, lists and tuples
Dictionaries GENOME 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Conditionals (if-then-else)
Ruth Anderson UW CSE 160 Winter 2017
While loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Ruth Anderson UW CSE 160 Spring 2018
For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble Notes for 2010: I skipped slide 10. This is.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Using files Taken from notes by Dr. Neil Moore
Fundamentals of Programming I Files
File Handling.
Strings Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Last Class We Covered Escape sequences File I/O Uses a backslash (\)
More for loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
While loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Sequence comparison: Local alignment
Notes about Homework #4 Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming:
Introduction to Python
Introduction to Python
Topics Introduction to File Input and Output
While loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
“Everything Else”.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Topics Introduction to File Input and Output
CS 1111 Introduction to Programming Spring 2019
Files A common programming task is to read or write information from/to a file.
How to read from a file read, readline, reader
Presentation transcript:

File input and output Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble Notes from 2009: Sample problem 4, the description differs from the example. First “if-else” slide, must define seq.

<filehandle> = open(<filename>, <access type>) Opening files The open() command returns a file object. <filehandle> = open(<filename>, <access type>) Python can read, write or append to a file: 'r' = read 'w' = write 'a' = append Create a file called “hello.txt” containing one line: “Hello, world!” >>> my_file = open("hello.txt", "r")

Why is there a blank line here? Reading the whole file You can read the contents of the file into a single string. >>> my_string = my_file.read() >>> print my_string Hello, world! >>> Why is there a blank line here?

Reading the whole file Now add a second line to your file (“How ya doin’?”) and try again. >>> my_file = open("hello.txt", "r") >>> my_string = my_file.read() >>> print my_string Hello, world! How ya doin'? >>>

Reading the whole file Alternatively, you can read the file into a list of strings. >>> my_file = open("hello.txt", "r") >>> my_string_list = my_file.readlines() >>> print my_string_list ['Hello, world!\n', "How ya doin'?\n"] >>> print my_string_list[1] How ya doin'?

Reading one line at a time The readlines() command puts all the lines into a list of strings. The readline() command returns the next line. >>> my_file = open("hello.txt", "r") >>> my_string = my_file.readline() >>> print my_string Hello, world! How ya doin'? >>>

Writing to a file Open the file for writing or appending. >>> my_file = open("new.txt", "w") Use the <file>.write() method. >>> my_file.write("This is a new file\n") >>> my_file.close() >>> ^D > cat new.txt This is a new file Always close a file after you are finished reading from or writing to it.

Print vs write <file>.write() does not automatically append an end-of-line character. <file>.write() requires a string as input >>> new_file.write("foo") >>> new_file.write(1) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: argument 1 must be string or read-only character buffer, not int

<file> = open(<filename>, r|w|a) <string> = <file>.read() <string> = <file>.readline() <string list> = <file>.readlines() <file>.write(<string>) <file>.close()

Sample problem #1 Write a program read-first-line.py that takes a file name from the command line, opens the file, reads the first line, and prints the result to the screen. > python read-first-line.py hello.txt Hello, world! >

Solution #1 import sys filename = sys.argv[1] my_file = open(filename, "r") first_line = my_file.readline() my_file.close() print first_line

Sample problem #2 Modify your program to print the first line without an extra carriage return. > python read-first-line.py hello.txt Hello, world! >

Solution #2 import sys filename = sys.argv[1] my_file = open(filename, "r") first_line = my_file.readline() first_line = first_line[:-1] my_file.close() print first_line

Sample problem #3 Write a program add-two-numbers.py that reads one integer from the first line of one file and a second integer from the first line of a second file and then prints their sum. > add-two-numbers.py nine.txt four.txt 9 + 4 = 13 >

Solution #3 import sys file_one = open(sys.argv[1], "r") value_one = int(fileOne.readline()) file_two = open(sys.argv[2], "r") value_two = int(fileTwo.readline()) print value_one, "+", value_two, "=", value_one + value_two

Sample problem #4 (optional) sample.txt: 1 2 3 4 5 Write a program called print-nth-line.py that will extract a specified line from a given file. python print-nth-line.py 2 sample.txt 2

Solution #4 import sys lineNumber = int(sys.argv[1]) file_name = sys.argv[2] infile = open(file_name, "r") lines = infile.readlines() print lines[lineNumber - 1]

Reading Chapter 14 of Think Python (1st edition) by Allen B. Downey.