Chapters 7&8: Files and Lists Flashcards
“Thank you/nYou’re welcome”
When printed, returns:
Thank you
You’re welcome.
/n = 1 charactcer, new line. If simply entered, will show initial version.
fhand=open(‘blah.txt’)
Opens the given text file if it exists in the python directory (in quick access). Value fhand is assigned with is only the file handle. But some subsequent functions, but not print, will be done on entire text file.
x=fhand.read()
assigns actual text of file to x as a string, not just handle
x.rstrip()
strips white space from right of the string, but NOT left. as opposed to lstrip or just strip
lift only lines starting with ‘From:’ from file, getting rid of double spacing.
fhand=open('givenfile.txt') for line in fhand: line=line.rstrip() if line.startswith('From:'): print(line)
text=banana
text.find(‘c’)
returns -1, as no c in banana.
lift only lines containing given substr, getting rid of double spacing
fhand=open('givenfile.txt') for line in fhand: line=line.rstrip() if line.find('given_substr')==-1: continue print(line)
if blah blah: continue
same effect as:
if blah blah:
continue
newtext=open(‘output.txt’, ‘w’)
Write mode (second parameter, w). This creates new file, or overwrites existing file with then entered name if it exists.
writing lines
line1=’This is the first line\n’
newtext.write(line1)
returns 24, number of characters entered.
finish writing
newtext.close()
list vs string
both sequences of values: string values are characters, list values cacn be anything
values of a list
called elements or items. comma and space between them, enclosed in square brackets, strings have speech marks numbers and variables dont (as usual). Lists within lists work as you’d think - lists, within square brackets, just become another element.
print 1st item in a list
print(list[0])
reassign 3rd item in a list to x
list[2]=’x’