File Handling Flashcards
Which import is required?
import os
How to open a file?
f = open(‘logs.dat’, ‘r’)
What are these operators for?
‘r’
‘w’
‘a’
‘r+’
‘b’
‘t’
read-only mode
write-only mode
appending mode, write-only
opened for reading/writing
binary mode
text mode
How to read all lines of a file?
f = open(‘logs.txt’, ‘r’)
lines = f.readlines()
while i <= len(lines):
do something…
f.close()
How to write to a file?
f = open(‘logs.txt’, ‘w’)
f. write(“This is a text”)
f. close()
What’s the difference between write & writelines?
- writelines expects an iterable of strings
- write expects a single string
How to copy a file using a python function?
import shutil
shutil.copy(oldfile, newfile)
How to copy a file using a standard code?
fin = open(oldfile,'r') fout = open(newfile,'w')
aList = fin.readlines()
for line in aList:
fout.write(line)
fin. close()
fout. close()