Files A common programming task is to read or write information from/to a file.

Slides:



Advertisements
Similar presentations
Computer Science 111 Fundamentals of Programming I Files.
Advertisements

Reading Files Chapter 7 Python for Informatics: Exploring Information
Creating an HTML page Skills: edit and debug HTML pages IT concepts: text editor This work is licensed under a Creative Commons Attribution-Noncommercial-
“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?
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Agenda Getting Started: Using Unix Unix Structure / Features Elements of the Unix Philosophy Unix Command Structure Command Line Editing Online Unix Command.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Files Tutor: You will need ….
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
1 Project 3 String Methods. Project 3: String Methods Write a program to do the following string manipulations: Prompt the user to enter a phrase and.
Files in Python The Basics. Why use Files? Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
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.
Development Environment
Reading Files Chapter 7 Python for Everybody
Introduction to Computing Science and Programming I
Topic: File Input/Output (I/O)
CSE 103 Day 20 Jo is out today; I’m Carl
Introduction to Programming
Writing & reading txt files with python 3
Python: Experiencing IDLE, writing simple programs
Introduction to Python
File I/O File input/output Iterate through a file using for
(optional - but then again, all of these are optional)
Python Lists Chapter 8 Python for Everybody
Lecture 24: print revisited, tuples cont.
Variables, Expressions, and IO
Managing results files
Vi Editor.
Data File Import / Export
Engineering Innovation Center
Python for Informatics: Exploring Information
File input and output Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble Notes from 2009: Sample problem.
Python I/O.
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
File IO and Strings CIS 40 – Introduction to Programming in Python
More Loops.
Fundamentals of Programming I Files
File I/O File input/output Iterate through a file using for
Learning to Program in Python
Escape sequences: Practice using the escape sequences on the code below to see what happens. Try this next code to help you understand the last two sequences.
Fundamentals of Data Structures
Introduction to Python: Day Three
Introduction to Programming
Chapter 2 Basic vi Editor.
How to save information in files open, write, close
Python programming exercise
Files Handling In today’s lesson we will look at:
Topics Introduction to File Input and Output
Python Basics with Jupyter Notebook
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
“Everything Else”.
Input and Output Python3 Beginner #3.
Python - Files.
CSE 231 Lab 5.
Introduction to Programming
Topics Introduction to File Input and Output
Nate Brunelle Today: Web Reading
How to read from a file read, readline, reader
Strings String basics String formatting.
Lists basics A container is a construct used to group related values together and contains references to other objects instead of data. A list is a container.
1.3 Compression, Encryption & Hashing
Presentation transcript:

Files A common programming task is to read or write information from/to a file.

Files: reading from files A common programming task is to read or write information from/to a file. Let’s first see how to read from a file: 1) Download the file source.txt from our web-page and place it into Documents folder 2) type in the following command in the Python Shell: >>> mySource = open(“source.txt”) source.txt 1 1.4 1.6 -4

Files: reading from files A common programming task is to read or write information from/to a file. Let’s first see how to read from a file: 1) Download the file source.txt from our web-page and place it into Documents folder 2) type in the following command in the Python Shell: >>> mySource = open(“source.txt”) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> mySource=open("source.txt") FileNotFoundError: [Errno 2] No such file or directory: 'source.txt'

Files: reading from files A common programming task is to read or write information from/to a file. 3) Create a new file in Python Editor, type in the following commands and save the file in the Documents folder mySource = open(“source.txt”) for line in mySource: print(line) mySource.close() 4) Run it! source.txt : 1 1.4 1.6 -4

Methods for reading from a file: Files: reading from files Methods for reading from a file: method Description open(<filename>) opens a file named <filename> close() closes an opened file read() reads everything from a file and returns it as string readlines() returns a list of strings readline() reads one line from a file and returns it as a string for i in f Iterates over the lines in a file (i is a line from the file)

Files: reading from files source.txt : 1 1.4 1.6 -4 We can replace the previous program: mySource = open(“source.txt”) for line in mySource: print(line) mySource.close() with: mySource = open("source.txt") text = mySource.read() print(text) Python Shell: 1 1.4 1.6 -4

Files: reading from files What if we want to find the sum of all numbers in a file? source.txt 1 1.4 1.6 -4

Files: reading from files What if we want to find the sum of all numbers in a file? mySource = open(“source.txt”) s = 0 for line in mySource: s += float(line) mySource.close() print(“The sum of all values is”,s) source.txt 1 1.4 1.6 -4

Files: reading from files What if we want to find the sum of all numbers in a file? mySource = open(“source.txt”) s = 0 for line in mySource: s += float(line) mySource.close() print(“The sum of all values is”,s) source.txt 1 1.4 1.6 -4 The sum of all values is 0.0 You can find this program in the file workWithFiles3.py

Files: reading from files What if we want to find the sum of all numbers in a file, but the source file is formatted differently? - the numbers are separated by a space or by a new line source2.txt 1 8 9.2 -5 1.4 9 8 0 12 -23 -9 1 1.6 2.3 -9.1 -42 -91 76 23 7

Files: reading from files What if we want to find the sum of all numbers in a file, but the source file is formatted differently? - the numbers are separated by a space or by a new line mySource = open("source2.txt") s = 0 for line in mySource: line = line.rstrip() numbers = line.split(" ") for item in numbers: s += float(item) mySource.close() print("The sum of all values is",s) source2.txt 1 8 9.2 -5 1.4 9 8 0 12 -23 -9 1 1.6 2.3 -9.1 -42 -91 76 23 7 You can find this program in the file workWithFiles4.py

Files: reading from files In-class activity 1 What if we want to find the sum of all numbers in a file, but the source file is formatted differently? - the numbers are separated by a comma and by a new line Modify the program in the file workWithFiles4.py to accommodate the new formatting. source3.txt 1,8,9.2,-5 1.4,9,8,13 0,12,-23,-9,1 1.6,2.3,-9.1,-5 -42,-91,7,23,17

Files: writing to files Let’s first see how to write to a file: Type in the following in the Python Shell: >>> myOut = open(“out.txt”,’w’) >>> myOut.write(“Hello, my name is Fran.\n”) >>> myOut.write(“I like to dance ”) >>> myOut.write(“and sing.”) >>> myOut.close() Let’s try to find the file we just created: Try the folder where all the programs you worked today with are.

Files: writing to files Let’s first see how to write to a file: Type in the following in the Python Shell: >>> myOut = open(“out.txt”,’w’) >>> myOut.write(“Hello, my name is Fran.\n”) >>> myOut.write(“I like to dance ”) >>> myOut.write(“and sing.”) >>> myOut.close() Let’s try to find the file we just created: Try the folder where all the programs you worked today with are. Or, do the following: >>> myOut = open("out.txt") >>> print(myOut.read())

Files: writing to files We can add more to the file that already exists: Type in the following in the Python Shell: >>> myOut = open(“out.txt”,’a’) >>> myOut.write(“I went to the circus today.”) >>> myOut.close() Then find the file and see how it changed. Or, do the following: >>> myOut = open("out.txt") >>> print(myOut.read()) You can find this program in the file workWithFiles5.py

Methods for writing to a file Files: writing to files Methods for writing to a file method description open(<filename>,’w’) open(<filename>,’a’) open the file for writing (‘w’) or appending (‘a’) write(<text>) writes a string <text> to a file

Files: writing to files Example: let’s ask the user to enter a positive integer n and a file name, create a file with the given file name and put the squares of the first n positive integers into it, separated by space. n = int(input("Enter a positive integer:")) if n > 0: fname = input("Please enter a file name:") output = open(fname + ".txt",'w') for i in range(1,n+1): output.write(str(i*i)+' ') output.close() print("Done! Look for the file",fname+'.txt') else: print("positive integer is expected!") You can find this program in the file workWithFiles6.py

Files: writing to files In-class activity 2 Modify the program we just did (see file workWithFiles6.py) to output the squares of the first n positive integers into it, separated by new line character (‘\n’), i.e. one value per line. out.txt 1 4 9 16 25 36

Proceed to in-class activities 3-4 Files: writing to files Proceed to in-class activities 3-4

This OER material was produced as a result of the CS04ALL CUNY OER project. This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 4.0 License.