Basic Python Programming: for loops and reading files


Basic Python Programming: for loops and reading files cover page
March 16, 2006 Linguist’s Guide to Python http://www. zacharski.org/python 3 Basic Python Programming: for loops and reading files In the last tutorial we covered a range of topics … … including lists and how to define your own functions. In this tutorial we will continue this whirlwind introduction to Python and cover what are called for loops and also learn how to read information from files. The next tutorial, Tutorial 4, will be our ‘easy day’—a breather. In that tutorial we will go through a set of exercises that will …

56 For example, suppose I have a folder on my C drive called ‘AI’, in that folder is another folder called ‘python’, and in that folder is the file I want to read, ’sample.txt’. Windows1 specifies the directory path for this as: C:\AI\python\sample.txt In Chapter 1 we noted that the backslash character ‘\’ has special meaning in Python strings—namely that the next character should be interpreted in some special way. In order to get actual backslashes in a Python string we need to put a backslash before each of them. For example: filename = ‘C:\\AI\\python\\sample.txt’ Writing all these backslashes can become tedious, so in most cases, you can use a shorthand provided by Python. Put the single character ‘r’ (for ‘raw string’) at the front of your string (with no space): filename = r’C:\AI\python\sample.txt’ Note that Python sees the same thing regardless of whether you type the extra backslashes or you put the ‘r’ in front (as long as you do one of them): >>> print ‘C:\\AI\\python\\sample.txt’ C:\AI\python\sample.txt >>> print r’C:\AI\python\sample.txt’ C:\AI\python\sample.txt Now that we’ve identified our filename, we can open this file for reading: infile = open(filename, ‘r’) or infile = open(r’C:\AI\python\sample.txt’, ‘r’) Reading information from the file In the next line in the sample above, lines = list(infile) the list () function creates a list from all the lines of the file (in this case all the lines of sample.txt). This list is then assigned the name lines. For example, if sample.txt contained the lines: Ann 541-1360 Ben 541-1298 Sara 524-9963 1 Different operating systems specify paths differently. Windows specifies a path using backslashes (as in, \AI\Python\sample.txt) ; the Macintosh OS specifies a path using double colons (AI::Python::sample.txt) and Unix and Linux specify a path using forward slashes (/AI/Python/sample.txt) ,

Download Basic Python Programming: for loops and reading files.Pdf

One Response to “Basic Python Programming: for loops and reading files”

  1. it is better to upload and download files

Leave a Reply