9

I need to open a file from a different directory without using it's path while staying in the current directory.

When I execute the below code:

for file in os.listdir(sub_dir):
    f = open(file, "r")
    lines = f.readlines()
    for line in lines:
        line.replace("dst=", ", ")
        line.replace("proto=", ", ")
        line.replace("dpt=", ", ")

I get the error message FileNotFoundError: [Errno 2] No such file or directory: because it's in a sub directory.

Question: Is there an os command I can use that will locate and open the file in sub_dir?

Thanks! -let me know if this is a repeat, I searched and couldn't find one but may have missed it.

1
  • you need to add the sub_dir path to your file in the open() function to be able to open it. Commented Aug 22, 2013 at 20:14

3 Answers 3

13

os.listdir() lists only the filename without a path. Prepend these with sub_dir again:

for filename in os.listdir(sub_dir):
    f = open(os.path.join(sub_dir, filename), "r")

If all you are doing is loop over the lines from the file, just loop over the file itself; using with makes sure that the file is closed for you when done too. Last but not least, str.replace() returns the new string value, not change the value itself, so you need to store that return value:

for filename in os.listdir(sub_dir):
    with open(os.path.join(sub_dir, filename), "r") as f:
        for line in f:
            line = line.replace("dst=", ", ")
            line = line.replace("proto=", ", ")
            line = line.replace("dpt=", ", ")
Sign up to request clarification or add additional context in comments.

5 Comments

If I wanted to write the new line to filename, would I add f.write(line) and open in a mode?
@hjames: Sure, just adjust the mode parameter of the open() call.
Hmm, if I put it in a or w mode, it returns an error that the file isn't readable. If I put it in r mode it obviously can't write to the file.
io.UnsupportedOperation: not readable or io.UnsupportedOperation: not writable
@hjames: Do you need to open the file for both reading and writing? Then use r+ or w+ (open existing file, r will leave existing data there, w will truncate existing files).
11

You must give the full path if those files are not in the current directory:

f = open( os.path.join(sub_dir, file) )

I would not use file as a variable name, maybe filename, since this is used to create a file object in Python.

Comments

-1

Code to copy files using shutil

import shutil
import os

source_dir = "D:\\StackOverFlow\\datasets"
dest_dir = "D:\\StackOverFlow\\test_datasets"
files = os.listdir("D:\\StackOverFlow\\datasets")

if not os.path.exists(dest_dir):
    os.makedirs(dest_dir)

for filename in files:
    if file.endswith(".txt"):
        shutil.copy(os.path.join(source_dir, filename), dest_dir)

print os.listdir(dest_dir)

Comments

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.