01. Perform Input and Output Operations 1 Flashcards
How many arguments does the open function in python use?
Two arguments.
- the path to the file
- The mode, i.e. read, write, append, binary
workFile = open(‘Jacket’, ‘r’)
In the following code example, the file has been opened, read and the contents displayed onscreen. The user is finished with the file.
What is the next line of code?
workFile = open(‘Jacket’, ‘r’)
workFileContents = workFile.read()
print(workFileContents)
workFile = open(‘Jacket’, ‘r’)
workFileContents = workFile.read()
print(workFileContents)
workFile.close()
The following code example reads the entire contents of a file.
What changes must be made to read the first line only.
workFile = open(‘Jacket’, ‘r’)
workFileContents = workFile.read()
print(workFileContents)
workFile.close()
workFile = open(‘Jacket’, ‘r’)
workFileContents = workFile.readline()
print(workFileContents)
workFile.close()
In the following example, the file ‘log.txt’ does not exist on the local hard drive.
Will this script create a file or not?
writeFile = open(‘log.txt’, ‘w’)
toLog = input(‘What do you want to write to the log?’ )
writeFile.write(tolog)
writeFile.close()
Yes, the script will create a file if one does not exist.
If you have previously created the file in the example below, and decide to rerun the script to add more content, what will happen?
writeFile = open(‘log.txt’, ‘w’)
toLog = input(‘What do you want to write to the log?’ )
writeFile.write(tolog)
writeFile.close()
The contents of the file will be rewritten upon each execution of the code.
Python has a library called import os which is short for operating system
- List some of the most common functions that this library contains.
- It can be used to check if a file exists or not using os.path.isfile(‘log,txt’)
The following code example is missing one line. The objective is to delete the file ‘log_old.txt’
What is the missing line of code?
import os
if os.path.isfile(‘log_old.txt’):
missing code
print(‘The log_old file has been removed’)
else:
print(‘There was no log_old file to remove)
import os
if os.path.isfile(‘log_old.txt’):
_os.remove(‘log_old.txt’)_
print(‘The log_old file has been removed’)
else:
print(‘There was no log_old file to remove)
In the following code example, what purpose does the “with” statement serve?
with open(‘log.txt’, ‘w’) as writeFile:
toLog = input(‘What do you want to write to the log? ‘)
writeFile.write(toLog)
The ‘with’ statement ensures the file can be properly closed. It also removes the need to write the previous close way of writeFile.close()
WIP - EXPLORE ALL THE DIFFERENT WAYS TO DO FORMATTED TEXT
WIP - EXPLORE ALL THE DIFFERENT WAYS TO DO FORMATTED TEXT