Presentation is loading. Please wait.

Presentation is loading. Please wait.

OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files.

Similar presentations


Presentation on theme: "OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files."— Presentation transcript:

1 OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files

2 OCR Computing GCSE © Hodder Education 2013 Slide 2 Python 10: Files This section looks at text files. You can also work with other types of files such as binary files in Python. Creating and writing to a text file When working with files, we need to set up a variable to refer to the file. This is known as a file descriptor or file handle. my_file=open('my_file.txt','w') my_file is the handle open() activates the file my_file.txt is the physical file on the disk 'w' means write to file. If the file does not exist it will be created. If it does exist, it will be overwritten.

3 OCR Computing GCSE © Hodder Education 2013 Slide 3 Python 10: Files Here is some code that uses the file write method. Each item is followed by a new line character (\n) to create separate lines in the file. This will make processing easier later. We close the file after use with the close method.

4 OCR Computing GCSE © Hodder Education 2013 Slide 4 Python 10: Files You can use any text editor to inspect the file that has been written. The new file will look something like this in Windows:

5 OCR Computing GCSE © Hodder Education 2013 Slide 5 Python 10: Files Appending data to a file If you want to add data to a text file, using the ‘w’ method is no good; it will overwrite your existing file. Use the ‘a’ (append) method instead.

6 OCR Computing GCSE © Hodder Education 2013 Slide 6 Python 10: Files Reading from a file As you would expect, we need the read method and use ‘r’ to open it.

7 OCR Computing GCSE © Hodder Education 2013 Slide 7 Python 10: Files The readline method does just that: it reads one line from the file. Usually you will want more control. Use the readlines (plural) method for that.

8 OCR Computing GCSE © Hodder Education 2013 Slide 8 Python 10: Files You can specify just one line to output by putting the line number in square brackets. Here, we ask for line 2. This gives you:


Download ppt "OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files."

Similar presentations


Ads by Google