Consider a file example.txt containing the text "Hello World". What will be printed by the following code?
with open('example.txt', 'r') as f: content = f.read(5) print(content)
The read(n) method reads n characters from the file starting at the beginning.
The code reads only the first 5 characters from the file, which are "Hello". It does not read the entire file.
Given a file data.txt that already contains some text, what will be the content of the file after running this code?
with open('data.txt', 'w') as f: f.write('New content')
Opening a file in 'w' mode clears its content before writing.
Mode 'w' opens the file for writing and truncates it to zero length, so old content is removed.
What error will this code raise if missing.txt does not exist?
with open('missing.txt', 'r') as f: data = f.read()
Opening a file in read mode requires the file to exist.
Trying to open a non-existent file in 'r' mode raises FileNotFoundError.
Assume log.txt initially contains "Start\n". What will be the content after running this code?
with open('log.txt', 'a') as f: f.write('End\n')
Mode 'a' appends to the file without deleting existing content.
Opening in append mode adds new text at the end, so original content remains.
Choose the file mode that opens a file for both reading and writing, but does not erase the existing content when opened.
One mode allows reading and writing and keeps existing content intact.
Mode r+ opens for reading and writing without truncating. w+ truncates, a+ appends, x+ creates new file only.