Worksheet #24090802 Introduction to files
Multiple Choice Questions (MCQs)
- What type of file stores data in a human-readable format?
- a) Binary File
- b) CSV File
- c) Text File
- d) Image File
- Which of the following modes opens a file for writing and reading, truncating the file to zero length?
- a) r+
- b) w+
- c) a+
- d) r
- In Python, what does the
readline()
method do?- a) Reads a single character
- b) Reads a line from the file
- c) Writes a line to the file
- d) Reads the entire file at once
- Which method is used to write a single line of text to a file?
- a) writeline()
- b) write()
- c) writechar()
- d) appendline()
- What is the default mode in which a file is opened if no mode is specified?
- a) w
- b) r
- c) a
- d) r+
- Which method is used to move the file pointer to a specific position in a file?
- a) seek()
- b) move()
- c) tell()
- d) point()
- In which mode can you read and append to a file without truncating it?
- a) r+
- b) a+
- c) w+
- d) r
- Which of the following is an example of an absolute path?
- a)
/home/user/documents/file.txt
- b)
documents/file.txt
- c)
./file.txt
- d)
../file.txt
- a)
- What is the difference between the
read()
andreadlines()
methods?- a)
read()
reads a single line,readlines()
reads the entire file - b)
read()
reads the entire file,readlines()
reads a single line - c)
read()
reads the entire file,readlines()
reads all lines as a list - d) Both methods do the same thing
- a)
- Which file mode is used to open a file for appending data without reading its content?
- a) a
- b) w
- c) r+
- d) w+
Programming Questions
- Write a Python program to open a text file, write “Hello, World!” to the file, and close it.
- Create a program that reads a text file and displays its content line by line using
readline()
. - Write a program to append a new line of text to an existing file. If the file does not exist, create it.
- Write a Python program that reads the first 10 characters of a text file and displays the file pointer position using
tell()
. - Develop a program to copy the content of one text file to another text file.
- Write a Python program to open a file using the
with
clause and read the entire file usingread()
. - Create a program that opens a text file and reads its content until the end of the file using a loop.
- Write a program that reads a CSV file and prints each row in the file.
- Develop a Python program that opens a text file, moves the file pointer to the middle of the file using
seek()
, and reads the next 20 characters. - Write a Python program that counts the number of lines, words, and characters in a text file.