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
*
asterisk. multiplication
”
double quote. defines beginning and end of strings
’’’
triple simple quote. for opening multiple lines of text
{}
curly brackets. variables inside strings
[]
square brackets. for building lists
format()
passes arguments filling placeholders marked as {}
\n
new line
\t
tab (indents in string)
import
imports a module
argv
module that requests an argument to function
int()
converts string into an integer
float()
converts a string into a number with decimal
input()
request input from user
open()
The open() function opens a file, and returns it as a file object.
open(“demofile.txt”, “r”)
truncate()
The truncate() method resizes the file to the given number of bytes.
If the size is not specified, the current position will be used.
file.truncate(size)
def
defines a function. this is how every function should begin/
def name_of_function(argument1, argument2):
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.
file.readline(size)