2.2.1
File Handling
Files
Files
Without files we can only store data in the memory.
Files
Files
- Files allow us to store data so that it persists even when our program is not running.
- This allows programs to 'carry on where they left off' when they are executed.
Text files
Text files
- Text files consist of string data that can be read and processed by many applications.
Binary files
Binary files
- Binary files consist of binary data that is read and processed by specific applications.
File Handling
File Handling
We must be careful with the way that we access files so that we do not accidentally corrupt them.
Open the file
Open the file
- First we open the file for use, so that the operating system knows that we are using it.
- We can do this using:
- open("filename.txt", "r")
- open("filename.txt", "w")
- Opening with "r" will allow you read access to the file.
- Opening with "w" will allow you write access to the file.
Assign the file to a variable
Assign the file to a variable
- The file must be assigned to a variable so that we can keep refering to it.
- This can be done as follows:
- myFile = open("filename.txt", "r")
- myFile = open("filename.txt", "w")
Read / write
Read / write
- We can now read or write to the file using the following commands:
- myFile.readline() will return the next line of a file as a string.
- myFile.write(
) will write a line to the file.
Close the file
Close the file
- Finally we must close the file so that it is free for another program to access.
- We can do this using:
- myFile.close()
1Introduction to Python
1.1Python
1.2Input & Output
1.3Data Types
1.4Variables & Constants
1.6Program Flow
2Data Structures
2.1Lists & Strings
2.2File Handling
3Modularity
3.1Subroutines
3.2Data Flow
4Good Practice
4.1Naming & Whitespace
4.2Comments
4.3Exceptions
Jump to other topics
1Introduction to Python
1.1Python
1.2Input & Output
1.3Data Types
1.4Variables & Constants
1.6Program Flow
2Data Structures
2.1Lists & Strings
2.2File Handling
3Modularity
3.1Subroutines
3.2Data Flow
4Good Practice
4.1Naming & Whitespace
4.2Comments
4.3Exceptions
Unlock your full potential with GoStudent tutoring
Affordable 1:1 tutoring from the comfort of your home
Tutors are matched to your specific learning needs
30+ school subjects covered