[python] Do I need to pass the full path of a file in another directory to open()?

I have a folder with ten files in it which I want to loop through. When I print out the name of the file my code works fine:

import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)

Which prints:

1
2
3
4
5
6
7
8
9
10

But if I try to open the file in the loop I get an IO error:

import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        log = open(f, 'r')

Traceback (most recent call last):
File "/home/des/my_python_progs/loop_over_dir.py", line 6, in <module>
log = open(f, 'r')
IOError: [Errno 2] No such file or directory: '1'
>>> 

Do I need to pass the full path of the file even inside the loop to open() them?

This question is related to python file-io absolute-path

The answer is


If you are just looking for the files in a single directory (ie you are not trying to traverse a directory tree, which it doesn't look like), why not simply use os.listdir():

import os  
for fn in os.listdir('.'):
     if os.path.isfile(fn):
        print (fn)

in place of os.walk(). You can specify a directory path as a parameter for os.listdir(). os.path.isfile() will determine if the given filename is for a file.


You have to specify the path that you are working on:

source = '/home/test/py_test/'
for root, dirs, filenames in os.walk(source):
    for f in filenames:
        print f
        fullpath = os.path.join(source, f)
        log = open(fullpath, 'r')

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

The examples to os.walk in the documentation show how to do this:

for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        log = open(os.path.join(root, f),'r')

How did you expect the "open" function to know that the string "1" is supposed to mean "/home/des/test/1" (unless "/home/des/test" happens to be your current working directory)?


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to absolute-path

Server Document Root Path in PHP Do I need to pass the full path of a file in another directory to open()? PHP absolute path to root How to use relative/absolute paths in css URLs? src absolute path problem Relative path to absolute path in C#? Get filename and path from URI from mediastore Convert absolute path into relative path given a current directory using Bash How to get the file-path of the currently executing javascript code Resolve absolute path from relative path and/or file name