In [20]:
# open is used to open a file object
f = open('README.md', 'r')
In [21]:
# The different modes availabe are
# r -> for reading the file
# w -> for writing to the file
# a -> for appending to the file i.e. adding to the last
# r+ -> for both reading and writitng
In [22]:
# Always use with keyword to open a file as it ensures that the file is closed properly
with open('README.md', 'r') as f:
read_data = f.read() # read is used to get the contents of the opened file
f.closed
# without the with keyword you should close the file as
# f.close
Out[22]:
In [32]:
with open('Sample.txt', 'r') as f:
for line in f:
print(line)
f.closed
Out[32]:
In [35]:
with open('Sample.txt', 'r') as f:
first_line = f.readline() # Introduces \n at the end of lines
second_line = f.readline()
last_line = f.readline()
f.closed
print(first_line)
print(second_line)
print(last_line)
In [38]:
with open('Sample.txt', 'w') as f:
f.write('This is the test line\n')
f.closed
Out[38]:
In [39]:
# To save complex data types like lists use JSON
# It can take Python data hierarchies and convert them to string -> serializing
# Reconstruct the data from string -> deserializing
In [41]:
# To view json representation of an object
import json
data = [1,2,'a']
json.dumps(data)
Out[41]:
In [42]:
data = {'one':1, 'two':2}
json.dumps(data)
Out[42]:
In [46]:
# Write the json object to a file
with open('Sample.txt', 'w') as f:
json.dump(data, f)
f.closed
Out[46]:
In [50]:
# Get the json object from the file
with open('Sample.txt', 'r') as f:
x = json.load(f)
f.closed
x
Out[50]:
In [ ]: