Python code
Python code

Reputation: 11

Python code to check if a filename is present in a text file

I am new in python, the requirement is like i have one flat file where it mentioned 3 files name, i need to check the file name written in flat file it exist in directory or not. Below mentioned is my code. but everytime it showing me file doesnt exist where as file present.

my flatfile name is filename.txt. where i have 3 entry

I need to read file name line by line and check the file present in directory or not. but i am not sure why this code is not working. flat file as well as 3 file present in same directory

with open('filename.txt','r') as f:
    line = f.readlines()
    print(line)
    for fh in line:
        print(fh)
        if path.exists(fh):
            print (fh,"File exist")
        else:
            print (fh,"File not exist")
            sys.exit(0)

Upvotes: 1

Views: 905

Answers (2)

balderman
balderman

Reputation: 23815

The code below will create a dict where the file name points to a boolean telling if the file exists or not.

from os import path
with open('filename.txt','r') as f:
    file_names = [l.strip() for l in f.readlines()]
    exists = {fn: path.exists(fn) for fn in file_names}

Upvotes: 0

Masklinn
Masklinn

Reputation: 42217

That is because readlines includes the trailing newline character.

So you need to strip it manually (generally using str.strip or str.rstrip for more safety) as your filenames likely don't include a newline.

That aside, readlines isn't really necessary here, you can just iterate on the file directly. However, you really should provide an explicit encoding to open when using it in text mode, otherwise it uses whatever garbage locale.getpreferredencoding(False) returns and that is often not what you want (especially on windows systems).

Upvotes: 4

Related Questions