myfile = open('foo.txt')
data = myfile.read()
myfile.close()
data
'Hello there!'
myfile = open('foo.txt','w')
myfile.write("Hello there!")
myfile.close()
--------------------------------------------------------------------------- UnsupportedOperation Traceback (most recent call last) Input In [12], in <cell line: 2>() 1 myfile = open('foo.txt') ----> 2 myfile.write("Hello there!") 3 myfile.close() UnsupportedOperation: not writable
myfile = None
def step1():
global line
myfile = open("foo.txt","w")
myfile.write("222 This is line")
myfile.write("555 This is another line")
def step2():
myfile = open("foo.txt")
print("I read",myfile.read())
step1()
step2()
I read 222 This is line555 This is another line
primes = [2,3,5,7,9]
primes[0:3]
[2, 3, 5]
primes[3:6]
[7, 9]
primes[0:3] + primes[3:6]
[2, 3, 5, 7, 9]
# primes[a:b] + primes[b:c] == primes[a:c]
primes.remove(9)
primes
[2, 3, 5, 7]
p2 = list(primes)
p2.append(11)
primes
[2, 3, 5, 7]
p2
[2, 3, 5, 7, 11]
for row in open('foo.txt').read():
print(row)
H e l l o t h e r e ! T h i s i s a f i l e . I w a n t a b u n c h o f l i n e s i n i t . T h i s w a y I c a n d o a n e x a m p l e .
for row in open('foo.txt').read().split("\n"):
print(row)
Hello there! This is a file. I want a bunch of lines in it. This way I can do an example.
open('foo.txt').read().split("\n")
['Hello there!', 'This is a file.', 'I want a bunch of lines in it.', 'This way I can do an example.', '']
open('foo.txt').readlines()
['Hello there!\n', 'This is a file.\n', 'I want a bunch of lines in it.\n', 'This way I can do an example.\n']
open('foo.txt').readline()
'Hello there!\n'
myfile = open('foo.txt')
myfile.readline()
'Hello there!\n'
myfile.readline()
'This is a file.\n'
myfile.readline().strip()
'I want a bunch of lines in it.'
def writeNumbers(name,a,b):
myfile = open(name,'w')
myfile.write(str(a)+"\n")
myfile.write(str(b)+"\n")
myfile.close()
def averageNumbers(name):
myfile = open(name)
a = int(myfile.readline())
b = int(myfile.readline())
print("The average is",(a+b)/2)
writeNumbers("test.txt",10,20)
averageNumbers("test.txt")
The average is 15.0