Computer science
  • Exam boards
    • OCR past papers >
      • Paper1 (Sample)
    • Edexcel past papers >
      • 2020 Current spec (coming soon) >
        • Programming Language Subset (PLS)
      • Old 2016 SPEC >
        • Paper 1 (specimen1)
        • Paper 1 (specimen2)
        • Paper 1 (2018)
        • Paper 1 (2019)
        • Paper 2 (specimen1)
        • Paper 2 (2018)
        • Paper 2 (2019)
      • OLD 2013 SPEC >
        • Sample assessment 1 (old spec)
        • Sample assessment 2 (old spec)
        • June 2017 (old spec)
        • June 2016 (old spec)
        • June 2015 (old spec)
    • Paper 1 (by topic) >
      • Algorithms
      • Application software
      • Ascii
      • Binary
      • Cache
      • Client Server
      • Cloud
      • Compression
      • Computational thinking
      • CPU
      • Cyber security
      • Database
      • Fetch decode execute cycle
      • Embedded system
      • Encryption
      • File size
      • Flow chart
      • Hexadecimal
      • High Level language
      • ISP/Internet
      • Logic
      • Magnetic HDD
      • Networking
      • Open source
      • Operating system
      • Peer to peer
      • Images (Data representation)
      • Protocols
      • RAM
      • ROM
      • Run length encoding
      • Simulation software
      • Solid state HDD
      • Sound
      • Stored program concept
      • Utility software
    • Curriculum >
      • Binary
      • Hex
      • Data Representation
      • Compression
      • Encryption
      • What is a computer
      • How does a computer work
      • Hardware
      • Operating system
      • The CPU
      • Input devices
      • Data storage
      • Networks
      • Microcontrollers
      • Computational models
      • Emerging trends
      • Virtual machine
      • Models and simulators
      • Algorithms
    • Python >
      • Finding python
      • GCSE Python questions
      • Python coding >
        • Comments
        • Data types
        • Variables
        • If Else
        • If Elif Else
        • Functions
        • For loop
        • While loop >
          • While loop challenges
        • Data structures >
          • Looping thru 2D array
        • String slicing/indexing
        • Subprograms
        • Local/global variable
        • Validation and try
        • methods
        • File I/O
        • Pseudocode
        • Modules >
          • Turtle
        • Classes
        • NEA/Projects
  • KS3/Other
    • KS3 >
      • Online Safety >
        • Screen time
        • Online Safety questions
      • IT
      • Hardware >
        • All Hardware
        • Magnetic hard disk drive
        • Optical disk drive
        • Solid state drive
      • Software
      • Binary/Hex/Algorithms >
        • Binary
        • Binary explained
        • Hexadecimal - 1 digit
        • Hexadecimal - 2 digits
        • Algorithms
        • ASCII
        • Tests
      • Networks
      • Protocols/Cyber attacks
      • Logic >
        • CPU
        • AND gate
        • OR gate
        • NOT gate
        • Logical statements
      • Coding >
        • HTML
        • Scratch >
          • Scratch questions
        • Python >
          • Getting started
          • Functions
          • Variables
          • VariablesToo
          • inputs
          • Selection
          • Flowcharts
          • Data types
          • Pseudocode1
          • Pseudocode2
          • Subprogram1
          • Subprogram2
          • Coding challenges
    • BTEC CS
    • OCR GCSE CS >
      • Past paper JUNE 2015
      • Past paper June 2014
      • Past paper MAY 2012
      • Past paper JAN 2011
      • Past paper JUN 2011
    • AQA AS-Level CS >
      • AS Curriculum >
        • Multiple choice questions
    • Business studies >
      • Keywords
      • BS Revision - Multiple choice
      • Paper 1 (9-1)
      • Paper 2 (9-1)
  • Contact/More
    • Code editor
    • Contact us
    • Microbit ideas
    • More
  • Self test
    • 01 Random topics
    • 02 Programming
    • 03 Data
    • 04 Computers
    • 05 Networks
    • 06 Legal/Ethics/Enviro'
    • Coding/Programming

Python coding

PYTHON DICTIONARY


Comments

Data types

Variables

If Else

If Elif Else

Functions

For loop

While loop

Data structures

String slicing/indexing

User defined function

Local/Global variable

Validation and Try

Methods

File I/O

Pseudocode

Modules​

What does file I/O even mean?

File input/output.

​You can use python to read strings from plain text files e.g. Microsoft notepad. Equally you can use Python to write to a text file.

This is a very useful facility for Python to either save information or load information.

Picture

Basic file operations

​Function
Desciption
Example
​  <fileIid>= open(<filename>, "r")
Opens file for reading
stuff = open("newbook.txt", "r")
for <line> in <fileid>
Reads every line, one at a time
for line in book
<alist> = <fileid>.readlines()
​Returns a list where each item is a line from the file
myList = book.readlines()
print(myList)
<aline> = <fileid>.readline()
​Returns a line from a file. Returns an empty
string on the end of the file
line = book.readline()
<fileid> = open(<filename>, "w")
​Opens file for writing
myBook = open("original.txt", "w")
<fileid> = open(<filename>, "a")
​Opens file for appending
myBook = open("original.txt", "a")
<fileid>.writelines(<structure>)
​Writes <structure> to a file. <structure> is
a list of strings
myBook.writelines(["monday","Tuesday"])
<fileid>.write(<aString>)
​Writes a single string to a file
myBook.write("hi")
<fileid>.close()
​Closes file
myBook.close()

Working with text files

in Windows, "Notepad" is the name of the program that lets you make "text files". Search for it on your Windows device, it should be there.
Notice below how the text file and python file are saved in the same folder. They must be saved in the same folder otherwise your code will not "see" your text file. 
Picture

Python challenge - writing to a text file

Enter the following code in a Python code editor. Before running the code, what do you think it will do? Press "F5" then "Enter" to run
Picture

In this example, the "w" means "write" which means to add what ever the user writes into the text file called read_it. "Write" and "close" are methods for the variable called notepad which hold the value of the created and opened "read_it.txt" file. "w" is not the only mode of opening a file. Below is a table that shows all the other modes available.

CHALLENGE: Extend the code above to ask for Last name and age and then save the data in the text file as First name and Surname on one line and age on the next line below.

Python challenge - Reading from text file

Download the following text file from here. Enter the following code below in a Python code editor. Save both the code and the downloaded text file in to the same folder (rename the text file as "lines.txt"). Before running the code, what do you think it will do? Press "F5" then "Enter" to run
Picture
Picture

Selected text file access modes

Mode
Description
"r"
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. If the file doesn't exist, Python will give an error message.
"w"
Write to a text file. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
"a"
Append a text file. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
"r+"
Opens a file for both reading and writing. The file pointer placed at the beginning of the file. If the file doesn't exist, Python will give an error message.
"w+"
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
"a+"
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. If the file does not exist, it creates a new file for reading and writing.

Selected file object methods

Method
Description
.close()
Closes the file. A closed file cannot be read from or written to until opened again
.read([size])
Read size characters from the file and returns them as a string
.readlines([size])
Reads one entire line from the file. A trailing newline character is kept in the string. If size is not specified, this method will return all the text from the current position to the end of the file
.readlines()
Reads one entire line from the file.  A size can be specified in the brackets
.write(output)
Writes a string to the file
.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.

Python challenge - writing to a text file

Enter the following code in a Python code editor. Before running the code, what do you think it will do? Press "F5" then "Enter" to run
Picture
Here a user defined function contains code that opens the text file called "lines.txt". There is a for loop that reads every line of the poem in the text file and brings it into an empty array called "SomeData_list". More about {.replace} and {.split} can be found in methods. More about the return statement can be found here.
Home
Contact
Upload
Log in
  • Exam boards
    • OCR past papers >
      • Paper1 (Sample)
    • Edexcel past papers >
      • 2020 Current spec (coming soon) >
        • Programming Language Subset (PLS)
      • Old 2016 SPEC >
        • Paper 1 (specimen1)
        • Paper 1 (specimen2)
        • Paper 1 (2018)
        • Paper 1 (2019)
        • Paper 2 (specimen1)
        • Paper 2 (2018)
        • Paper 2 (2019)
      • OLD 2013 SPEC >
        • Sample assessment 1 (old spec)
        • Sample assessment 2 (old spec)
        • June 2017 (old spec)
        • June 2016 (old spec)
        • June 2015 (old spec)
    • Paper 1 (by topic) >
      • Algorithms
      • Application software
      • Ascii
      • Binary
      • Cache
      • Client Server
      • Cloud
      • Compression
      • Computational thinking
      • CPU
      • Cyber security
      • Database
      • Fetch decode execute cycle
      • Embedded system
      • Encryption
      • File size
      • Flow chart
      • Hexadecimal
      • High Level language
      • ISP/Internet
      • Logic
      • Magnetic HDD
      • Networking
      • Open source
      • Operating system
      • Peer to peer
      • Images (Data representation)
      • Protocols
      • RAM
      • ROM
      • Run length encoding
      • Simulation software
      • Solid state HDD
      • Sound
      • Stored program concept
      • Utility software
    • Curriculum >
      • Binary
      • Hex
      • Data Representation
      • Compression
      • Encryption
      • What is a computer
      • How does a computer work
      • Hardware
      • Operating system
      • The CPU
      • Input devices
      • Data storage
      • Networks
      • Microcontrollers
      • Computational models
      • Emerging trends
      • Virtual machine
      • Models and simulators
      • Algorithms
    • Python >
      • Finding python
      • GCSE Python questions
      • Python coding >
        • Comments
        • Data types
        • Variables
        • If Else
        • If Elif Else
        • Functions
        • For loop
        • While loop >
          • While loop challenges
        • Data structures >
          • Looping thru 2D array
        • String slicing/indexing
        • Subprograms
        • Local/global variable
        • Validation and try
        • methods
        • File I/O
        • Pseudocode
        • Modules >
          • Turtle
        • Classes
        • NEA/Projects
  • KS3/Other
    • KS3 >
      • Online Safety >
        • Screen time
        • Online Safety questions
      • IT
      • Hardware >
        • All Hardware
        • Magnetic hard disk drive
        • Optical disk drive
        • Solid state drive
      • Software
      • Binary/Hex/Algorithms >
        • Binary
        • Binary explained
        • Hexadecimal - 1 digit
        • Hexadecimal - 2 digits
        • Algorithms
        • ASCII
        • Tests
      • Networks
      • Protocols/Cyber attacks
      • Logic >
        • CPU
        • AND gate
        • OR gate
        • NOT gate
        • Logical statements
      • Coding >
        • HTML
        • Scratch >
          • Scratch questions
        • Python >
          • Getting started
          • Functions
          • Variables
          • VariablesToo
          • inputs
          • Selection
          • Flowcharts
          • Data types
          • Pseudocode1
          • Pseudocode2
          • Subprogram1
          • Subprogram2
          • Coding challenges
    • BTEC CS
    • OCR GCSE CS >
      • Past paper JUNE 2015
      • Past paper June 2014
      • Past paper MAY 2012
      • Past paper JAN 2011
      • Past paper JUN 2011
    • AQA AS-Level CS >
      • AS Curriculum >
        • Multiple choice questions
    • Business studies >
      • Keywords
      • BS Revision - Multiple choice
      • Paper 1 (9-1)
      • Paper 2 (9-1)
  • Contact/More
    • Code editor
    • Contact us
    • Microbit ideas
    • More
  • Self test
    • 01 Random topics
    • 02 Programming
    • 03 Data
    • 04 Computers
    • 05 Networks
    • 06 Legal/Ethics/Enviro'
    • Coding/Programming