0

I made a simple program to test this out. It simply finds any instance of a specific string, and replaces it with a new string. What I want to do is run this against my entire directory, file by file.

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        f = open(file,'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(file, 'w')
        f.write(newdata)
        f.close()

But I keep getting an error message telling me that one of files doesnt exist in my directory, even though it does. I can't figure out why it would tell me that.

1
  • 3
    os.listdir just returns the filenames, they don't have the directory prefix. Use os.path.join to connect them. Commented Mar 1, 2016 at 17:25

2 Answers 2

1

os.listdir() returns a list of strings much like the terminal command ls. It lists the names of the files, but it does not include the name of the directory. You need to add that yourself with os.path.join():

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        file = os.path.join(directory, file)
        f = open(file,'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(file, 'w')
        f.write(newdata)
        f.close()

I would not recommend file as a variable name, however, because it conflicts with the built-in type. Also, it is recommended to use a with block when dealing with files. The following is my version:

def replace(directory, oldData, newData):
    for filename in os.listdir(directory):
        filename = os.path.join(directory, filename)
        with open(filename) as open_file:
            filedata = open_file.read()
            newfiledata = filedata.replace(oldData, newData)
            with open(filename, 'w') as write_file:
                f.write(newfiledata)
Sign up to request clarification or add additional context in comments.

Comments

1

Try this way :

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        f = open(os.path.join(directory, file),'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(os.path.join(directory, file), 'w')
        f.write(newdata)
        f.close()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.