term1 Definition1term2 Definition2term3 Definition3
Please sign in to your Google account to access your documents:
opening a file
Opening the file communicates with your operating system which knows where the data for each file is stored. When you open a file, you are asking the operating system to find the by name and make sure the file exists.
fhand = open('filename.txt')
print fhand
newline character
In Python we use backslash--n in string constants.
>>> stuff = 'X\nY'>>> print stuffXY
startswith()
Checks what a string starts with like this
fhand = open('mbox-short.txt')for line in fhand:if line.startswith('From:') :print line
would print all lines starting with From:
Writing files
To write a file you have to open it with mode 'w' as a second parameter.
>>> fout = open('output.txt', 'w')>>> print fout
The write method of the file handle object puts data into the file.>>> line1 = 'This here's the wattle,\n'>>> fout.write(line1)Again, the file object keeps track of where it is, so if you call write again, it addsthe new data to the end.
repr()
Takes any object as an argument and returns a string representation of the object. For strings, it represents whitespace characters with backslash sequences:
>>> s = '1 2\t 3\n 4'>>> print s1 2 3 4
>>> print repr(s)'1 2\t 3\n 4'
Need help typing ? See our FAQ (opens in new window)
Please sign in to create this set. We'll bring you back here when you are done.
Discard Changes Sign in
Please sign in to add to folders.
Sign in
Don't have an account? Sign Up »
You have created 2 folders. Please upgrade to Cram Premium to create hundreds of folders!