File Objects
create a file called demo.txt in the same directory as my Python file. Then let’s see how we can open and read this file from within Python now.
OPEN FILES:
f = open('demo.txt', 'r')
print(f.name)
f.close()
Here ‘r’ just for reading, ‘w’ just for writing and ‘r+’ for reading and writing
Remember to close the file that you open.
with open('demo.txt','r') as f:
pass
In this way, you don’t need to close the file.
READ FILES :
f.read()
with open('demo.txt','r') as f:
f_contents = f.read()
print(f_contents)
#print out all of the contents of our file
with open('demo.txt','r') as f:
f_contents = f.read(10)
print(f_contents)
#print out 10 characters of our file
f.readline()
with open('demo.txt','r') as f:
f_contents = f.readlines()
print(f_contents)
#get the next line in our file
LOOP
with open('demo.txt','r') as f:
for line in f:
print(line, end=' ')
with open('demo.txt','r') as f:
size_to_read = 5
f_contents = f.read(size_to_read)
while len(f_contents) > 0:
print(f_contents, end='@')
f_contents = f.read(size_to_read)
#divide the content with 'size_to_read'
f.tell()
return the postion in the file
f.seek(#int)
set position
WRITE FILES:
with open('demo2.txt','w') as f:
pass
If this file didn’t exit, this will create it.
If this file already exited, this will overwrite it.
COPY TEXT
with open('demo.txt','r') as rf:
with open('demo2.txt','w') as wf:
for line in rf:
wf.write(line)
COPY PICTURE
with open('1.jpg', 'rb') as rf:
with open('2.jpg', 'wb') as wf:
for line in rf:
wf.write(line)
‘b’ for binary mode
with open('1.jpg', 'rb') as rf:
with open('2.jpg', 'wb') as wf:
chunk_size = 4096
rf_chunk = rf.read(chunk_size)
while len(rf_chunk) > 0:
wf.write(rf_chunk)
rf_chunk = rf.read(chunk_size)
for more information in docs.python.org