input - Using python to achieve replace function -


i trying operate file this:

*sline 1, 1.0, 2.23 2, 1.0, 9.98 3, 2.0, 10.00 *eline 

now have list, contain data this:

datalist = [[1,1.0,2.0],[3,2.0,2.0]] 

i want put value belong datalist replace value in file id(datalist[][0]), like:

*sline 1, 1.0, 2.0 2, 1.0, 9.98 3, 2.0, 2.0 *eline 

i try utilse:

o = open("file","a")  line in open("trychange.txt"):    line = line.replace("1, 1.0, 2.23","1, 1.0, 2.0")    line = line.replace("3, 2.0, 10.00","3, 2.0, 2.0")    o.write(line + "\n")  o.close() 

but doesn't work, add new values didn't change old one. how can deal this? helping

  1. open file "r" mode , read contents.

    • while reading in contents of file (strings) convert lines easy-to-process data structures (e.g.: list of integers...)
  2. process previous read contents in memory.

    • note while read in file (or after reading file) can build several auxiliary data structures support in carrying out operations on data. example in case in-memory data structure should include list contains data each line, , dictionary helps lookup lines using 2 numbers. see example below.
  3. open file again "w" mode , overwrite previous file new data.

    • you can convert in-memory data string line-by-line.
    • if want "safe" overwrite first create temporary file, write out new data, , rename temp file original one. note on unix rename technique can used "atomically change file contents". way shouldn't end partially saved file.

example in memory data structure:

lines = [     [1, 1.0, 2.23],     [2, 1.0, 9.98],     [3, 2.0, 10.00], ]  key_to_lines_index = {     (1, 1.0): 0,  # 0 index lines array     (2, 1.0): 1,  # 1 index lines array     (3, 2.0): 2,  # 2 index lines array } 

with above in memory data structure can apply datalist items easily. each datalist item can use key_to_lines_index dictionary lookup line have modify , modify corresponding line in lines array. when finished write out modified file lines array.

if isn't enough job done have problem understanding fundamental principles of programming right place continue this: https://wiki.python.org/moin/beginnersguide/programmers


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -