Module 10 - File Access Flashcards
What do you call a program that runs all the time and keeps at least some of its data in permanent storage?
A persistent program
example: operating systems and web servers
How do you read a line from a text file? Write the sample code.
use open function and assign to variable:
fin = open (‘words.txt’)
then use readline method:
fin.readline ( )
What is a text file?
A sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM
How do you write a file?
You have to open it with mode ‘w’ as a second parameter:
fout = open(‘output.txt’, ‘w’)
What are the two types of files? What is the difference?
Text file - contains data that has been encoded as text
Binary file - contains data that has not been converted to text
What are the two types of access to data stored in a file?
Sequential access - file read sequentially from beginning to end, can’t skip ahead
Direct access - can jump directly to any piece of data in the file
What is a filename extension and what does it indicate?
Short sequence of characters at the end of filename (after the period)
Indicate the type of data stored in the file
What’s a file object? What’s the point of it?
Object associated with a specific file
Provides a way for a program to work with the file: file object referenced by a variable
What’s the ‘open’ function used for and what does it do? What’s the syntax?
Used to open a file
It creates a file object and associates it with a file on the disk
file_object = open (filename, mode)
What are the different modes of the ‘open’ function?
Mode is the second parameter in the function
Reading only - ‘r’
Writing - ‘w’
Appending - ‘a’
What happens if the open function receives a filename that does not contain a path?
It assumes that file is in the same directory as the program
If a program is running and a file is created, where is it created? Can you alter this?
In the same directory as the program
Can specify alternative path and file name in the open function argument - prefix the path string literal with the letter r
What is a method?
A function that belongs to an object
Performs operations using that object
How do you write data to a file?
File object’s write method
file_variable.write(string)
How do you close a file?
File object’s close method
file_variable.close( )