Additional programming techniques
Basic File Handling Operations in Python
Basic File Handling Operations in Python
File handling is a crucial aspect of programming that allows you to read from and write to files.
Basic file operations:
- open
- read
- write
- close
When you deal with a file you will always have to open it to begin with, this then locks the file from other processes. After you have either read or written to the file you will need to close the file so other processes can now access it.
Open
- Purpose: To open a file for reading or writing.
- Syntax:
myFile = open("sample.txt")
- Note: The file needs to be stored as a variable. The name of the file will be in the string.
myFile = open("people.txt")
You need to be aware that python requires a second parameter in the open function.
# open to read only
myFile = open("people.txt", "r")
# open to write to file (wiping previous contents)
myFile = open("people.txt", "w")
# open to append to file (keeping previous contents)
myFile = open("people.txt", "a")
Read
- Read Line:
- Purpose: To read the next line from the file.
- Syntax:
line = myFile.readline()
Example
- Open the file with read access.
- Use the readline() method on the file object to read the next line from the file
- that is stored as the variable line and then printed
myFile = open("sample.txt", "r")
line = myFile.readline()
print(line)
Write
- Write Line:
- Purpose: To write a line to the end of the file.
- Syntax:
myFile.write("Add new line\n")
Example
- Open the file with append access.
- Use the write() method on the file object to write to the end of the file, appending to the file
- Close the file when finished
myFile = open("sample.txt", "a")
myFile.write("Add new line\n")
myFile.close()
Python provides more than one way to write to a file.
In Python, the modes for opening files, w and a, are used for different purposes:
w (write mode): Opens a file for writing. If the file already exists, its content will be erased. If the file does not exist, it will be created.
Example: myFile = open("sample.txt", "w")
a (append mode): Opens a file for writing, but does not erase the content if the file already exists. Instead, new data will be added to the end of the file. If the file does not exist, it will be created.
Example: myFile = open("sample.txt", "a")
Close
- Purpose: To close an open file.
- Syntax:
myFile.close()
Example
myFile = open("sample.txt", "r")
myFile.close()
Example: Reading Until End of File
- Purpose: To read all lines in a file until the end.
Example
myFile = open("sample.txt", "r")
line = myFile.readline()
while line:
print(line.strip())
line = myFile.readline()
myFile.close()
Explanation
- Open: myFile = open("sample.txt", "r") opens the file in read mode. This is python specific and means the file cannot be editted only read.
- Initial Read: line = myFile.readline() reads the first line.
- Loop: while line: continues the loop as long as line is not empty.
- Print: print(line.strip()) prints the line, removing any extra newline characters.
- Read Next Line: line = myFile.readline() reads the next line in the file.
- Close: myFile.close() closes the file.
Create a New File
- Purpose: To create a new text file.
- Syntax: newFile = open("myText.txt", "w")
Example
newFile = open("myText.txt", "w")
newFile.write("This is a new file.\n")
newFile.close()
Explanation
Open: myFile = open("myText.txt", "w") opens the file in write mode. If the file doesn't exist it will be created
Write: newFile.write("This is a new file.\n") writes a string to the file.
\n: The \n character in programming represents a newline character. It is used to indicate the end of one line and the start of a new one. When a string containing \n is printed, the text following the \n will appear on a new line. When writing to a file, \n can be used to insert line breaks.
Close: myFile.close() closes the file.
User Input into a file
The following shows an example of taking user input and storing in the scores for each person using comma seperated values
# Open the file in append mode
myFile = open("sample.txt", "a")
# Initialize inputs
firstname = input("Enter your first name: ")
lastname = input("Enter your last name: ")
score = input("Enter your score: ")
while firstname != "" or lastname != "" or score != "":
myFile.write(firstname+","+lastname+","+score+"\n")
# Get user input
firstname = input("Enter your first name: ")
lastname = input("Enter your last name: ")
score = input("Enter your score: ")
# Close the file
myFile.close()
# Read and print the contents of the file
myFile = open("sample.txt", "r")
line = myFile.readline()
while line:
print(line.strip())
line = myFile.readline()
myFile.close()
In this example if the input data was
John Doe 85
Jane Smith 90
Alice Johnson 78
The output would be
John,Doe,85
Jane,Smith,90
Alice,Johnson,78
Explanation
- Open File for Appending: myFile = open("sample.txt", "a") opens the file in append mode.
- Initialize Inputs: Prompt the user to input their first name, last name, and score.
- Loop Until Exit Condition: The loop continues as long as not all inputs are empty strings.
- Write to File: Concatenate the inputs with commas and add a newline character, then write to the file.
- Get User Input Again: Continue to prompt for user input inside the loop.
- Close the File: Close the file after appending.
- Read and Print File: Reopen the file in read mode and print each line.
Hot Tip: Exam Technique
You will get marks in the exam for assigning a file to a variable
myFile = open("samplefile.txt")
and also for closing the file
myFile.close()
even if everything else is wrong, that is two marks for most file questions which is a grade 4.