File Handling Flashcards

1
Q

Which import is required?

A

import os

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to open a file?

A

f = open(‘logs.dat’, ‘r’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are these operators for?
‘r’
‘w’
‘a’
‘r+’
‘b’
‘t’

A

read-only mode
write-only mode
appending mode, write-only
opened for reading/writing
binary mode
text mode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to read all lines of a file?

A

f = open(‘logs.txt’, ‘r’)
lines = f.readlines()
while i <= len(lines):
do something…
f.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to write to a file?

A

f = open(‘logs.txt’, ‘w’)

f. write(“This is a text”)
f. close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What’s the difference between write & writelines?

A
  • writelines expects an iterable of strings
  • write expects a single string
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to copy a file using a python function?

A

import shutil
shutil.copy(oldfile, newfile)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to copy a file using a standard code?

A
fin = open(oldfile,'r')
fout = open(newfile,'w')

aList = fin.readlines()
for line in aList:
fout.write(line)

fin. close()
fout. close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly