1

I can print out names of all files in my current directory using the following python script:

import psycopg2
from config import config
import os

path = 'path_to_current_dir'
params = config()

conn = None
try:
    #read the connection parameters
    params = config()
    conn = psycopg2.connect(**params)
    cur = conn.cursor()

    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.plt'):
                print(file)
                #f = open(file, 'r')

    cur.close()
    conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
    print(error)
finally:
    if conn is not None:
        conn.close()

Output:

20090205094627.plt
20090312135415.plt
20090216055722.plt
20090311065333.plt
20090418032222.plt
20090119072534.plt

I want to read the content of each file, So I uncomment the open(..) statement in the script above. However, even the first file in the directory is not read, reporting the following error:

$ python check.py 
20090205094627.plt
[Errno 2] No such file or directory: '20090205094627.plt'

I am missing the right logic to read these files. How do I fix this?

2
  • Did you forget to prepend the subdirectory name to the file? You are only printing the filename, not the full (relative) path of the file. You'll need at least path. Commented Jun 10, 2020 at 12:27
  • You need to combine the directory name with the filename. The files are not in the directory from which you run the script. Commented Jun 10, 2020 at 12:27

1 Answer 1

3

You need to add the full path to the open function

f = open(os.path.join(root, file), 'r')

It will be better practice to open the file with with

with open(os.path.join(root, file), 'r') as f:
    f.read()

with with the file will close after exiting the with statement this way you will be sure that the file closes after you use it.

Sign up to request clarification or add additional context in comments.

2 Comments

Did it answer your question?
Sure, now I can carry on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.