Chapter 8 Flashcards
What is a more convenient function when we cannot use input() function to read large amounts of data?
We prepare the needed information as an external file and get our program to read the data in that external file.
What is the first step in making your program read an external file?
We create a .txt file with the text which we want our program to read and save it on desktop or a preferred location.
What’s the second step?
We write the below script and save it as .py file in the same folder as .txt
What does the first line in the program do?
f=open(‘myfile.txt’,’r’)
It opens the .txt file and reads it. r= read mode
open() function open the .txt file
the two arguments entail the path of the file and the mode
How would the first argument look like if the .txt and .py file weren’t saved in the same folder but a different folder in the C drive
Then the first argument would have been
‘C:\PythonFiles\myfile.txt’ (with double backslash \).
What is ‘w’ mode?
for writing only
What is ‘a’ mode?
for appending
What is ‘r+’ mode?
for both reading + writing
What does the next statement do?
firstline = f.readline()
It reads the first line in the .txt file and assigns it to the variable firstline
Each time the readline() function is called, it _______. In our program, readline() was called twice. Hence the______ will be read.
reads a new line from the file. first two lines
How would you tweak the code if you do not want the extra line between each line of the text?
print(firstline,end=’’)
its two single quotes
Why is it important to close the file?
to free up system resources
Write an example script for using the For loop for reading the text from the .txt file
Find the example attached with results
What mode will you use to write to a text file?
‘a’ append mode
Can we use the ‘w’ mode ?
we can. However, it will erase all the previous content in the file if it already exists