Topic 3 - Session 3 - MTA Intro Course Flashcards
To open a file in python, you need to specify two arguments, what are they?
- The file to be opened
2. The mode, i.e. read, write, append or binary.
See the example code below. Do you have to supply arguments to close a file?
workFile.close()
No
If you opened a file and wanted to read one line and assign it to a variable, what code would you use?
firstLine = workFile.readline()
Explain what is happening in the following code example
writeFile = open(‘log.txt’, ‘w’)
toLog = input(“Enter some text”)
writeFile.write(toLog)
writeFile.close()
- The first line is opening the file in write mode.
- User is prompted to enter some text.
- The data stored in the variable is written to the file.
- The file is closed.
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()
It would overwrite existing text.
If you need to create a new file on a system, what python library would you need?
import os
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')
- The required library is first imported.
- The if statement will check to see if the file exists. If it does, it will open it in append mode.
- Else, it will create the file and open in write mode.
Using the import os library, how would you delete a file?
os.remove(‘log_old.txt’)
When working with file, what is a better method of closing the file without using the close() function.
with open (‘log.txt’, ‘w’) as writeFile:
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.”)
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.”)
When working with files, what is the purpose of the ‘with’ statement.
This statement ensures a file is properly closed.