Ask Your Question
3

How can a Python script identify the files that have been downloaded and are listed in a .txt file?

asked 2022-06-07 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-06-23 19:00:00 +0000

huitzilopochtli gravatar image

Here's one way to approach the problem in Python:

  1. Read in the contents of the .txt file using the built-in open() function:
with open("downloaded_files.txt", "r") as f:
    downloaded_files = f.read().splitlines()

This will create a list called downloaded_files containing all the filenames listed in the .txt file.

  1. Use the built-in os library to check if each file exists in the current directory:
import os

for file in downloaded_files:
    if os.path.exists(file):
        print(f"{file} exists")
    else:
        print(f"{file} does not exist")

This code will loop through each filename in downloaded_files and use os.path.exists() to check if the file exists in the current directory. If the file exists, it will print a message saying so. If it doesn't exist, it will print a message saying so.

Note: This assumes that the .txt file lists filenames without any directory paths. If the filenames include directories, you'll need to modify the os.path.exists() check accordingly.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-07 11:00:00 +0000

Seen: 7 times

Last updated: Jun 23 '21