Python Flashcards
read()
The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.
f = open(“demofile.txt”, “r”)
print(f.read())
close()
The close() method closes an open file.
You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
readline()
The readline() method returns one line from the file.
You can also specified how many bytes from the line to return, by using the size parameter.
The number of bytes from the line to return. Default -1, which means the whole line.
f = open(“demofile.txt”, “r”)
print(f.readline())
truncate
empties the file
The truncate() method resizes the file to the given number of bytes.
If the size is not specified, the current position will be used.
f = open(“demofile2.txt”, “a”)
f. truncate(20)
f. close()
write(‘stuff’)
writes “stuff” to the file
The write() method writes a specified text to the file.
Where the specified text will be inserted depends on the file mode and stream position.
“a”: The text will be inserted at the current file stream position, default at the end of the file.
“w”: The file will be emptied before the text will be inserted at the current file stream position, default 0
f = open(“demofile2.txt”, “a”)
f. write(“See you soon!”)
f. close()
seek(0)
moves the read/write location to the beginning of the file
The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the screen.
(
opening parenthesis
)
closing parenthesis
#
Use ‘hashtag’ or ‘pound’ for commenting
+
plus sign. addition
/
slash. division
>
grater than
less than
’
single quote