• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/5

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

5 Cards in this Set

  • Front
  • Back

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 stuff
X
Y

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 adds
the 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 s
1 2 3
4


>>> print repr(s)
'1 2\t 3\n 4'