Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
21.
What is the purpose of the os.path.join() function in Python when working with file paths?
To create a new file
To concatenate multiple file paths
To check if a file exists
To rename a file
Answer: Option
Explanation:
os.path.join() is used to concatenate multiple file paths and create a valid path.

22.
How can you read the content of a binary file named "binary_data.dat"?
content = open("binary_data.dat").read()
content = open("binary_data.dat", "rb").read()
content = read_binary("binary_data.dat")
content = open_binary("binary_data.dat").read()
Answer: Option
Explanation:
To read the content of a binary file, the file should be opened with mode "rb".

23.
What is the purpose of the shutil.copy() function?
To move a file
To copy the contents of a file
To create a new file
To remove a file
Answer: Option
Explanation:
shutil.copy() is used to copy the contents of a file to another location.

24.
How can you read and print only the lines containing the word "Python" from a file named "text.txt"?
lines = open("text.txt").readlines()
    for line in lines:
    if "Python" in line:
        print(line)
with open("text.txt", "r") as file:
    for line in file:
        if "Python" in line:
            print(line)
print_python_lines("text.txt")
with open("text.txt", "r") as file:
    print(file.read("Python"))
Answer: Option
Explanation:
Using a for loop to iterate through the lines and printing lines containing "Python".

25.
What does the os.path.isfile() function check?
Checks if a path exists
Checks if a file is a binary file
Checks if a file is empty
Checks if a path points to a regular file
Answer: Option
Explanation:
os.path.isfile() checks if a path points to a regular file (not a directory).