Read all the text files in a folder and change a character in a string if it presents

4203 views python

I have a folder with csv formated documents with a .arw extension. Files are named as 1.arw, 2.arw, 3.arw ... etc.

I would like to write a code that reads all the files, checks and replaces the forwardslash / with a dash -. And finally creates new files with the replaced character.

The code I wrote as follows:

for i in range(1,6):
    my_file=open("/path/"+str(i)+".arw", "r+")

    if "/" not in str:
        print("There is no forwardslash")
        str_new = str.replace("/","-")

        f = open("/path/new"+str(i)+".arw", "w")

But I get an error saying:

'str' object is not callable.

How can I make it work for all the files in a folder? Apparently my for loop does not work.

answered question

You should not use str as a variable name, since python already uses it.

Any reason you prefer Python here instead of sed or awk?

Your code has obvious syntax errors, could you please edit to fix the indentation?

1 Answer


This is how I would do it:

for i in range(1,6):
    with open((str(i)+'.arw'), 'r') as f:
        data = f.readlines()

        for element in data:
            element.replace('/', '-')
    with open((str(i)+'.arw'), 'w') as f:
        for element in data:

posted this

Have an answer?


Please login first before posting an answer.