example.txt contains the text Hello World?with open('example.txt', 'r') as f: content = f.read() print(content)
read() method returns the whole file content as a string.The open function with mode 'r' opens the file for reading as text. The read() method reads the entire content as a string. So the output is the exact text inside the file.
with open('testfile.txt', 'w') as f: f.write('12345') with open('testfile.txt', 'r') as f: print(f.readline())
write method writes text, and readline reads one line as a string.The file is written with the string 12345. Then reading one line returns the whole string since there is no newline. So it prints 12345.
os.path to check file existencedata.txt does NOT exist in the current folder?import os if os.path.exists('data.txt'): print('Found') else: print('Not Found')
os.path.exists function returns True if the file exists, otherwise False.Since the file does not exist, os.path.exists returns False, so the else branch prints Not Found.
readonly.txt exists but is read-only?with open('readonly.txt', 'w') as f: f.write('Trying to write')
Trying to open a file with write mode 'w' when the file is read-only causes a PermissionError because the program lacks permission to modify the file.
pos?with open('numbers.txt', 'w') as f: f.write('1234567890') with open('numbers.txt', 'r') as f: f.read(4) pos = f.tell() print(pos)
tell() method returns the current position of the file pointer.The read(4) reads 4 characters, moving the file pointer 4 positions forward. So tell() returns 4.
