8.8 KiB
8.8 KiB
In [ ]:
%%writefile test.txt
Hello, this is a quick test file.In [ ]:
myfile = open('whoops.txt')In [ ]:
pwdIn [ ]:
# Open the text.txt we made earlier
my_file = open('test.txt')In [ ]:
# We can now read the file
my_file.read()In [ ]:
# But what happens if we try to read it again?
my_file.read()In [ ]:
# Seek to the start of file (index 0)
my_file.seek(0)In [ ]:
# Now read again
my_file.read()In [ ]:
# Readlines returns a list of the lines in the file
my_file.seek(0)
my_file.readlines()In [ ]:
my_file.close()In [ ]:
# Add a second argument to the function, 'w' which stands for write.
# Passing 'w+' lets us read and write to the file
my_file = open('test.txt','w+')In [ ]:
# Write to the file
my_file.write('This is a new line')In [ ]:
# Read the file
my_file.seek(0)
my_file.read()In [ ]:
my_file.close() # always do this when you're done with a fileIn [ ]:
my_file = open('test.txt','a+')
my_file.write('\nThis is text being appended to test.txt')
my_file.write('\nAnd another line here.')In [ ]:
my_file.seek(0)
print(my_file.read())In [ ]:
my_file.close()In [ ]:
%%writefile -a test.txt
This is text being appended to test.txt
And another line here.In [ ]:
%%writefile test.txt
First Line
Second LineIn [ ]:
for line in open('test.txt'):
print(line)In [ ]:
# Pertaining to the first point above
for asdf in open('test.txt'):
print(asdf)In [ ]: