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

4203 views python
2

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+")
    str=my_file.read()

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


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

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

10

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('/', '-')
        f.close()
    with open((str(i)+'.arw'), 'w') as f:
        for element in data:
            f.write(element)
        f.close()

posted this

Have an answer?

JD

Please login first before posting an answer.