Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 22

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 22 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 222018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 22)

Creatinga File object opens a file, either for reading or writing. The objectprovides various functions for accessing data in the opened file.The File object maintains a cursor that points at a specific location inthe file, depending on what you have read or written most recently. Everytime you read or write data to the file, the cursor is moved accordingly.As the cursor moves forward automatically, you can read through the fileonly once without explicitly repositioning or re-opening the file.Similarly, once you have written data to a file through the File object,you cannot read the newly written data from a file unless you repositionor re-open the object.

Conceptually, the cursor in the File object workssimilarly to the cursor in your text editor.FILE BASICS115Here is a simple example that opens a file, writes a string to it andreads the string from the file. After you have executed the script youshould see a new file, C:\python\test.txt, on your mobile device.Example 41: Basic file operationsf = file(u"c:\\python\\test.txt", "w+")print >> f, "Ip dip, sky blue"f.seek(0)print "File says", f.read()f.close()The first line opens the file. The file name must be specified as aUnicode string.

Note that the path names must be separated by doublebackslashes since a single backslash marks a special character in strings.The second parameter denotes the mode in which the file is opened.Here are the options:•w – the file is opened for writing. If the file already exists, it will beemptied first. Otherwise a new file is created.•r – the file is opened for reading in text mode. An exception isgenerated if the file does not exist.•a – the file is opened for writing. Writing continues at the end of file,if the file already exists.

Otherwise a new file is created.If a plus sign is added to the mode specifier, the file is opened inread–write mode, so you can both read from and write to the file usinga single file object. The difference between ‘w+’ and ‘r+’ is that, in theformer case, a new file is created if the file does not exist.The easiest way to write anything to a file is to use the print statement.In contrast to the ordinary print statement, you need to specify a targetfor printing, which is given as a file object preceded by double-arrows,>>:print >> f, "Ip dip, sky blue"Note that the print statement always adds a new line character afterthe written string. If you want to avoid this, you can use the file object’swrite() function.

In the example above, we could have written:f.write("Ip dip, sky blue")To read the newly created file, the file cursor must be repositionedback to the beginning. The function seek() performs this job. The value‘0’ specifies that the cursor is repositioned back to the beginning of the116DATA HANDLINGfile, which is the most typical use of the function. For other uses, see thePython documentation.There are three main ways to read text data from a file:•all at once: txt = f.read()•one line: line = f.readline()•a line at time: for line in f: print lineThere are also some other ways to read data which are described inthe Python documentation.

In Example 41, everything in the file is readat once and then printed to the console.The file is closed automatically when the file object is destroyed. Forinstance, this happens when you return from the function in which the fileobject was created, unless the variable holding the file object is definedas global.Note that only after closing the file can you be sure that its contentsare visible to other programs, as the file object may buffer data internally.To be on the safe side, you should call the close() function explicitlywhen you do not need the file, as we did in Example 41.6.1.3 Logging to a FileIn some cases, it is not feasible to leave the debugging output on theconsole. This might be the case if you need to output many debugginglines or you are using the standard application UI framework which hidesthe console output behind the application body.In cases like this, it is a good idea to redirect the debugging output toa file.

This is remarkably simple: just replace all print statements withprint >> logfile statements, where logfile is a variable containinga file object that has been opened, as in Example 41.If you are field-testing your program with, say, ten users, it makes senseto log all debugging events in a file. After the test session has ended,you can collect the log files and analyze the results. If you need a trulysophisticated solution, you can send the log files automatically to yourserver over a network connection. You can do this easily using techniquesthat are presented in Chapter 8.6.1.4 Finding Sound, Photo and Video FilesThe phone’s built-in camera application saves photos and videos and thesound recorder saves sounds to a convenient location in the directoryhierarchy of the phone, especially if you have set them to use the memorycard.

Note that some S60 2nd Edition devices may save files to otherlocations as well. Examples 42, 43 and 44 read files from the standardlocations.READING AND WRITING TEXT117Videos are found in 3rd Edition phones in the directory named Videos.The phone automatically creates a new subfolder for each month andyear when shooting a video. Example 44 reads a video that was recordedin March 2007.Example 42: Read a soundf = file("E:\\Sounds\\Digital\\boo.wav", "r")mysound = f.read()f.close()Example 43: Read an imagef = file("E:\\Images\\picture.jpg", "r")img = f.read()f.close()Example 44: Read a videof = file("E:\\Videos\\200703\\video.mp4","r")myvideo = f.read()f.close()6.2 Reading and Writing TextIf you need to read only one string from a file, say the user’s name, callingread() once is enough, as it reads the whole file at once.

But what ifyou need to read a list of strings instead?We could save the list items one to a line and read the file one lineat time. Note that list items are not allowed to contain line breaks in thiscase. Example 45 shows how to do this.Example 45: Read and write textdef save_list(filename, lst):f = file(filename, "w")for item in lst:print >> f, itemf.close()def load_list(filename):f = file(filename, "r")lst = []for line in f:lst.append(line.strip())f.close()return lst118DATA HANDLINGtest_list = ["first line", "second line", "that's all"]save_list(u"c:\\python\\test.txt", test_list)print load_list(u"c:\\python\\test.txt")This script should print out the contents of the list test list whenexecuted.

The function save list() writes each item of the given listto a file. The function load list() loads items from the file, readinga line at time in a loop, and appends each line to the list lst. Notethat we use the string function strip() to remove the trailing new linecharacters from lines that are read from the file. The list read from thefile is identical to the original list test list. A simple format like thismight be enough for saving, say, a list of URL bookmarks.6.2.1 Key–Value PairsWhat if a plain list of strings is not enough? For example, a configurationfile might contain several different fields, such as a user name, password,server name and port, all of which need to be accessed separately. A plainlist would not suffice, since we cannot know which line corresponds towhich field.In cases like this, key–value pairs come in handy.

Python has a usefuldata structure for accessing key–value pairs, namely the dictionary, thatwas briefly mentioned in Section 5.2. The language lesson describes theuse of the dictionary.Python Language Lesson: dictionaryThe dictionary object is used to save unique key–value pairs. It isa versatile data structure which is used in Python for many differentpurposes.You can create a new dictionary as follows:a = {}b = {"state": "CA", "zip": 94301}Here a contains an empty dictionary, defined with an empty pair ofcurly brackets. The variable b contains a dictionary that is initializedwith two key–value pairs: it contains the keys ‘state’ and ‘zip’ and thecorresponding values ‘CA’ and ‘94301’.Note that values can be any type of object, even File objects orimages, but key types have some restrictions. Simple types, such asstrings and numbers, may be used as keys.

Values are accessed withkeys as follows:READING AND WRITING TEXT119print b["state"]b["state"] = "NY"print b["state"]b["newkey"] = "new value"print b["newkey"]This above code prints out ‘CA’ followed by ‘NY’ and ‘new value’.You may change values and add new key–value pairs to the dictionaryfreely after it has been created. However, a key can map to only onevalue, so assigning a new value to an existing key replaces the previousvalue.

If you want to have multiple values per key, use a list as thevalue and append new items to it.A key–value pair can be deleted as follows:del b["state"]You can test if a key exists in a dictionary as follows:if "state"in b:print "state exists in the dictionary!"else:print "state does not exist in the dictionary"You can loop through all keys and values in the dictionary asfollows:for key, value in b.items():print "KEY", key, "VALUE", valueThe number of keys in the dictionary can be found with len(b).The dictionary supports a number of other operations as well. See thePython documentation for more information.6.2.2 Reading and Writing Named ValuesUsing dictionaries, we can develop functions for saving and loading aconfiguration file that consists of keys and values.

The format presentedhere is easy to read and edit manually. A downside is that only stringsare accepted as keys and values. Also, the saved strings must not containany new line characters or colons. In Section 6.3, you learn a moresophisticated way for saving information like this to a local database.120DATA HANDLINGWriting contents of a dictionary to a file is straightforward using theconcepts that we have just learnt.Example 46: Writing a dictionary to a filedef save_dictionary(filename, dict):f = file(filename, "w")for key, value in dict.items():print >> f, "%s: %s" % (key, value)f.close()One key–value pair is saved per line. The key and value strings areseparated by a colon character.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6381
Авторов
на СтудИзбе
308
Средний доход
с одного платного файла
Обучение Подробнее