![]() ![]() The next example is a short program that I used to generate some random data for the temps.txt data file.į.write(''.format(x, prediction, y)) In addition, should the program generate an error anywhere in the body the program will automatically exit the body of the with and close the file for us. Once we exit the body of the with construct the file will get closed for us automatically. The Python with construct is useful for this purpose. Since we always have to take care to close a file after we are done working with it, it may be helpful to use an alternative construction to manage opening and closing the file. When we are done reading the data from the file we use the close() method to close the file.We have to convert that string to a float before appending it to the list of temps. Each line in the text file is a string.We set up a for loop to iterate over this list of lines. f.readlines() returns an iterable list of lines in the text file.The parameter to open() specifies the name of the file to open. The open() function opens a file for reading and returns a file object. The first step in working with a file is to open the file.Here are some things to make note of in the program. The program will read the list of readings from the text file, put the readings in a list, and then determine and print the lowest and highest temperature readings found in the file. The readings are listed one per line in the text file. The program is designed to work with a text file that contains a list temperature readings. ![]() The example program below demonstrates the basics of working with data that comes from a text file. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |