Click here to Skip to main content
15,909,530 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to write some code to read an edit a text file in python. but am getting some really weird bugs that do not make sense to me.


Python
import fileinput
import linecache


def GetdataV1(Index,lineindex):#only works for Index3 and 2..every other index it will state "list index out of range"
    #Datafile = open("Trade data/Databaseforbot", "r")
    Linetoget = linecache.getline('Trade data/Databaseforbot', lineindex).split("|")
    Traddetail = Linetoget[Index].split("*")
    print(Traddetail[1])
    return Traddetail[1]






def PostdataV1(index,lineindex,data):#converts all to Hello instead of the specific part we wantot change to Hello
    # all 0's to "Hello"
    with fileinput.FileInput('Trade data/Databaseforbot', inplace=True, backup='.bak') as file:
        Datatoget = linecache.getline('Trade data/Databaseforbot', lineindex).split("|")
        finalvaluechange = Datatoget[index].split("*")
        #finalvaluechange = seperated.split("*")
        print(finalvaluechange[1])
        for line in file:
             print(line.replace(finalvaluechange[1], data), end='')



PostdataV1(3,1,"Hello")


What I have tried:

Some really weird bugs that do not make sense...as how can the index be out of list for 4 but not 3 or 2 when the .split forms 10 different parts

Also for the post if you do
PostdataV1(3,2)
it should return
this as the file

1|https://app.libertex.com/products/stock/BA/|3*34#34|4*0|5*0|6*0|7*0|8*0|9*0|CDwindow-76447D5BFE266B666CB3494980C5C4EB
2|https://app.libertex.com/products/stock/BA/|3*23#23|4*Hello|5*0|6*0|7*0|8*0|9*0|CDwindow-76447D5BFE266B666CB3494980C5C4EB

instead it edits the text file to look like this

1|https://app.libertex.com/products/stock/BA/|3*34#34|4*Hello|5*Hello|6*Hello|7*Hello|8*Hello|9*Hello|CDwindow-76447D5BFE266B666CB349498HelloC5C4EB
2|https://app.libertex.com/products/stock/BA/|3*23#23|4*Hello|5*Hello|6*Hello|7*Hello|8*Hello|9*Hello|CDwindow-76447D5BFE266B666CB349498HelloC5C4EB
where everywhere where there is a 0 there is"Hello"

Do you think its got anything to do with the fact im using * as the splitter?
Posted
Comments
Richard MacCutchan 21-Aug-20 3:04am    
where everywhere where there is a 0 there is"Hello"
That is what you told it to do in the line:
print(line.replace(finalvaluechange[1], data), end='')

where the data field is "Hello".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900