Files
- Open a file
f = open("DATA12.txt")
- You have two options for reading from a file
#1 - all the lines at once into a list
f = open("DATA12.txt")
lines = f.readlines()
f.close()
#loop through the lines list one line at a time
for line in lines:
print (line)
# OR
#pop the first line in the list, keep going until there's nothing more to pop
while True:
if len(lines) == 0:
break
line = lines.pop(0)
print (line)
#2 - one line at a time
f = open("input.txt")
while True:
line = f.readline()
if line == "":
break
print (line)
f.close()
Lists
#You can loop through a list in two ways:
#1 - itemized
numbers = [10, 45, 23, 56, 20]
for num in numbers:
print (num)
#2 - range
numbers = [10, 45, 23, 56, 20]
for i in range(len(numbers)):
print (numbers[i])
#Don't forget the very important list manipulation functions:
numbers = [10, 45, 23, 45, 20]
print (len(numbers)) #5
print (numbers[2]) #23
print (numbers.count(45)) #2
print (numbers.count(33)) #0
print (numbers.index(20)) #4
print (numbers.index(45)) #1
#print (numbers.index(17)) #CRASH (17 is not in the list)
numbers.sort() #sorts the list
print (numbers) #[10, 20, 23, 45, 45]
numbers.remove(23) #removes 23 from the list
print (numbers) #[10, 45, 45, 20]
#numbers.remove(17) #CRASH (17 is not in the list)
num = numbers.pop(0) #pops slot 0 from the list, stores result in num
print (num) #10
print (numbers) #[20, 45, 45]
numbers.append(55) #adds 55 to the end of the list
print (numbers) #[20, 45, 45, 55]
if 55 in numbers: #check if item 55 is in the numbers list
print ("yes") #yes!
else:
print ("no")
rstrip
#Sometimes (often) strings have \n at the end of them (it's invisible,
#it tells python that a new line has started). It's often beneficial
#to get rid of it because otherwise a string match may not work
line = line.rstrip()
split
#If your input line consists of multiple pieces of information separated
#by some delimiter, you can break tthem up into a list, like this (it
#gets rid of the \n and creates a list with 10 in slot 0, 30 in slot 2, etc)
line = "10 30 1 45"
line = line.rstrip().split(" ")
Decimal places
#Sometimes you need to display values to a specific decimal point.
num = 3.362718
print ("%0.3f" %num)
print ("%0.2f" %num)
Substrings
#Substrings in python are simple
x = "abcdefghijklmnop"
print (x[7:12])
#hijkl (from 7 to 12)
print (x[:5])
#abcde (from start to 5)
print (x[10:])
#klmnop (from 10 to end)
print (x[:-1])
#abcdefghijklmno (from start to one minus end