get names for file form text.txt file in python

To get names of the file from text.txt file, we can use the open function to open the file in read mode, read the contents of the file using readlines() method and then use string manipulation techniques to extract the file names.

Assuming the text.txt file contains the file names separated by a new line character, the following code can be used to read the file names one by one:

main.py
import os

# Open the text.txt file
with open("text.txt", "r") as file:
    # Read the contents of the file
    contents = file.readlines()

# Loop through the lines and extract the file names
for line in contents:
    # Remove the new line character
    line = line.strip()
    # Check if the file exists
    if os.path.isfile(line):
        # Print the file name
        print(line)
    else:
        # Print an error message
        print(f"Error: File '{line}' does not exist")
482 chars
19 lines

The os.path.isfile() function is used to check if a file exists at the specified path.

Note: The strip() function is used to remove any leading or trailing white spaces or new line characters from the file name.

gistlibby LogSnag