Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
41.
What is the purpose of the os.path.basename() function?
Returns the base name of a file or directory
Returns the absolute path of a file
Checks if a path is a regular file
Deletes a file
Answer: Option
Explanation:
os.path.basename() returns the base name of a file or directory.

42.
How can you read and print only the lines longer than 20 characters from a file named "data.txt"?
with open("data.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if len(line) > 20:
            print(line)
print_long_lines("data.txt", 20)
with open("data.txt", "r") as file:
    print(file.read(20))
lines = open("data.txt").readlines()
for line in lines:
    if line.length() > 20:
        print(line)
Answer: Option
Explanation:
Using len() to filter and print lines longer than 20 characters.

43.
What does the shutil.rmtree() function do?
Removes a file
Removes a directory and its contents
Renames a file
Copies a directory
Answer: Option
Explanation:
shutil.rmtree() removes a directory and its contents recursively.

44.
How can you copy a file named "source.txt" to a new location and rename it as "destination.txt"?
copy_file("source.txt", "destination.txt")
shutil.copy("source.txt", "destination.txt")
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
rename_file("source.txt", "destination.txt")
Answer: Option
Explanation:
Using shutil.copy() to copy and rename a file.

45.
How can you check if a file named "config.ini" exists?
if isfile("config.ini"):
if exists("config.ini"):
if file_exists("config.ini"):
if os.path.file_exists("config.ini"):
Answer: Option
Explanation:
Using exists() to check if a file exists.