Python Dictionaries

Writing text data to files:

The data writing and reading capabilities provided by the Curve object will probably take care of all the input-output needed to get through this course. At some point, you may be faced with the need for writing or reading files of a more general form. This section and the next covers the basics of how that is done. First you need to open the file. To do this, you type myfile = open(’test.out’,’w’) where myfile is the object by which you will refer to the file in your Python program. You can use any variable name you want for this. Similarly, you can replace test.out with whatever you want the file to be called. The second argument of open says that we want to create a new file, if necessary, and allow the program to write to it. You can only write a string to a file, so first you have to convert your data to a string. You have already learned how to do this. The following example serves as a reminder, and also shows how you can skip to a new line at the end of the string. a = 1. b=2. outstring = ’%f %f\n’%(a,b) outstring The definition of outstring tells Python to make a string converting the elements of the tuple from floats to characters, with a space in between and a carriage return (newline) at the end of the line. Files are objects in Python, so to write the string to the file, you just do myfile.write(outstring). Now you have everything you need to write space-delimited data to a file, except that when you are done, you need to close the file by executing myfile.close().Using what you have learned write a table of the functions x/(1 + x) and x 2/(1 + x 2 ) vs. x to a file. You can take a look at the resulting file in any text editor, or load the file into the program of your choice for plotting. 

Reading text data from a file:

To read text data from a file, you need to read in a line of text, and then convert the items into numbers, if that is what they represent. In order to do the conversion, it is necessary to know what kinds of items are in the file, although strings have various methods that can help you identify whether an item is a number or not. Conversion is done by string-to-number routines found in the module string. Strings representing integers can be converted to float numbers, but if you try to convert a string representing a float to an integer, you will get an error. The following example reads a single line from a file, which may consist of integers or floats separated by white-space characters, and converts it into a list of values. To read the rest of the file, you would repeat the procedure until the end of the file is reached. import string f = open("myfile.txt") buff = f.readline() items = buff.split() # Or, do it all at once with items = f.readline().split() values = [string.atof(item) for item in items]

Posted on by