Topic 3 - Session 3 - MTA Intro Course Flashcards

1
Q

To open a file in python, you need to specify two arguments, what are they?

A
  1. The file to be opened

2. The mode, i.e. read, write, append or binary.

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

See the example code below. Do you have to supply arguments to close a file?

workFile.close()

A

No

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

If you opened a file and wanted to read one line and assign it to a variable, what code would you use?

A

firstLine = workFile.readline()

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

Explain what is happening in the following code example

writeFile = open(‘log.txt’, ‘w’)
toLog = input(“Enter some text”)
writeFile.write(toLog)
writeFile.close()

A
  1. The first line is opening the file in write mode.
  2. User is prompted to enter some text.
  3. The data stored in the variable is written to the file.
  4. The file is closed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What would happen if you had entered some text and ran this section of code again?

writeFile = open(‘log.txt’, ‘w’)
toLog = input(“Enter some text”)
writeFile.write(toLog)
writeFile.close()

A

It would overwrite existing text.

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

If you need to create a new file on a system, what python library would you need?

A

import os

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

Explain what is happening with this following code

import os
if os.path.isfile('log.txt'):
   writeFile = open('log.txt', 'a')
else
   writeFile = open('log.txt', 'w')
A
  1. The required library is first imported.
  2. The if statement will check to see if the file exists. If it does, it will open it in append mode.
  3. Else, it will create the file and open in write mode.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Using the import os library, how would you delete a file?

A

os.remove(‘log_old.txt’)

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

When working with file, what is a better method of closing the file without using the close() function.

A

with open (‘log.txt’, ‘w’) as writeFile:

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

The following code is trying to print strings and integers. Instead of using type casting, what alternative could be used?

print(“We have “ + widgets + “ in stock.”)

A

Use formatted text instead.

Example:
The letter ‘f’ is added in front of quotation marks to indicate the presence of formatted text.

print(f”We have {widgets} widgets in stock.”)

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

When working with files, what is the purpose of the ‘with’ statement.

A

This statement ensures a file is properly closed.

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