Common functions for files…
Open file
open('file name', 'mode')
Specify the file name as an input parameter.
Specify the mode as a second parameter.
Mode | Syntax | Notes |
---|---|---|
Write | 'w' | Creates a new file if the file does not exist |
Append | 'a' | Creates a new file if the file does not exist |
Read | 'r' | Returns an error if the file does not exist |
Create | 'x' | Returns an error if the file does not exist |
The default mode is 'r' for read and does not need to be specified.
Optionally specify a second mode:
Mode | Syntax |
---|---|
Text mode | 't' |
Binary mode | 'b' |
The default value is 't' and does not need to be specified. Use 'b' for images.
Example:
myFile = open('sample.txt') # open text file.
data = myFile.read() # return file data as a string.
myFile.close() # close file.
Read file
Use r to read file.
Example:
myFile = open('sample.txt', 'r') # open file.
print(myFile.read()) # read file and display content.
Write file
Use w to write to a file. Overwrites existing file content.
Example:
myFile = open('sample.txt', 'w') # open file
myFile.write('My file content.') # specify string to write.
myFile.close() # close file.
myFile = open('sample.txt')
print(myFile.read())
My file content.
Example:
with open('sample.txt', 'w') as myFile: # open file.
myFile.write('My file content.') # specify string to write.
myFile = open('sample.txt')
print(myFile.read())
My file content.
Append content
Use a to append content to the end of a file.
Example:
with open('sample.txt', 'a') as myFile: # open file to append.
myFile.write('\nMy file additional content.') # specify string.
myFile = open('sample.txt')
print(myFile.read())
My file content.
My file additional content.