replace file Errror: string indices must be integers

Viewed 91

im an beginner in python. I dont understand the Error. Please can you help me?

import fileinput

ersetzendic = {
"abc":"TESTabc",
"ABC":"TESTABC",
"qwertz":"TESTqwertz",
"wtf":"TESTwtf",
"wtfee":"TESTwtf2"
}


for line in fileinput.input("readme.txt", inplace=True):
    for sonicsyntax in ersetzendic:
        ersetzendic = ersetzendic[sonicsyntax]
        line = line.replace(sonicsyntax,ersetzendic)
    print(line, end="" )

TypeError: string indices must be integers

6 Answers

when you write ersetzendic = ersetzendic[sonicsyntax] you are trying to access an str by a value that is not an int.

By the looks of it may be a tuple of (key, value) from your dict ersetzendic.

The code is (unnecessarily) overwriting the variable: ersetzendic in the line:

ersetzendic = ersetzendic[sonicsyntax]

so instead of an array of strings it turns into a string on the first iteration, and in the second iteration we're trying to access an index of that string using a string as a key - which is why it fails.

We can modify the last 3 lines from:

for sonicsyntax in ersetzendic:
    ersetzendic = ersetzendic[sonicsyntax]
    line = line.replace(sonicsyntax,ersetzendic)

to:

for sonicsyntax in ersetzendic: 
    line = line.replace(sonicsyntax, ersetzendic[sonicsyntax])

As far as I understand, you want to replace the words in a file which contains any of the keys in ersetzendic with their corresponding value in the dict. In your solution, the produced error was occurred due to this segment:

for sonicsyntax in ersetzendic:
    ersetzendic = ersetzendic[sonicsyntax]

With this, in the first iteration, you took a key from ersetzendic and reassigned ersetzendic taking the corresponding value of it. So that ersetzendic is now overwritten with a String value, that is not a dict anymore.

So, in the next iteration, when you're trying to repeat the thing, as ersetzendic is a string, accessing ersetzendic[something] is nothing but trying to accessing a character of specific index. Hence you're getting the error:

TypeError: string indices must be integers

However, you can take each line from the file, then each key of the dict ersetzendic and do a simple line.replace(target, replacingString) for your job. So, you can change the implementation as below:

for line in fileinput.input("readme.txt", inplace=True):
    for key in ersetzendic:
        line = line.replace(key,ersetzendic[key])
    print(line, end="" )

The error you are facing is cause of the line line = line.replace(sonicsyntax,ersetzendic) here ersetzendic is a string value which is one of the values stored in the dictionary cause of the line ersetzendic = ersetzendic[sonicsyntax] which changes your dictionary ersetzendic to a string. And you can not use str values to access strings.

I read in the comments about what you want to do. Here is how to fix it:

import fileinput

ersetzendic = {
"abc":"TESTabc",
"ABC":"TESTABC",
"qwertz":"TESTqwertz",
"wtf":"TESTwtf",
"wtfee":"TESTwtf2"
}

with fileinput.input(files=("readme.txt",), inplace=True) as input:    # using the context manager is a better way to read lines using the FileInput object
    for line in input:
        for sonicsyntax in ersetzendic:
            replacement_text = ersetzendic[sonicsyntax]    # store the value of the text to be reolaced in a new variable
            line = line.replace(sonicsyntax,replacement_text)    # pass the key as the first argument and the replacement text as the second
        print(line,end='')

This is what readme.txt looks like before the execution of the code:

abc
ABEABC
wtfrrrrrwtf
wtfgwtfee
qwertyqweertz

This is the file content after the code is executed:

TESTabc
ABETESTABC
TESTwtfrrrrrTESTwtf
TESTwtfgTESTTESTwtf2
qwertyqweertz

item is most likely a string in your code; the string indices are the ones in the square brackets. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.

If you do not want to use file input module. Then I have an easy solution. Look at this example -

txt file:

abc
ABC
qwe

Code:

with open('file.txt','r') as f: # Read The file
    lst = f.read().split()
    
for i in ersetzendic: # Replace desired elements
    lst = [ersetzendic[i] if x==i else x for x in lst]

with open('1.txt','w') as f: # Write to file
    for i in lst:
        f.write(i+'\n')

Result in .txt file:

TESTabc
TESTABC
qwe

I think you can implement this in your code!

Related