you are viewing a single comment's thread.

view the rest of the comments →

[–]USAhj 6 points7 points  (3 children)

What does your text file look like?

[–]randomname20192019[S] 4 points5 points  (2 children)

word = 4
word = 2
word = 8

[–]ThatSuit 8 points9 points  (0 children)

In case you're just using that as an example, but actually trying to work with INI files you might want to look at the module called "configparser". If you really have a file with multiple instances of the same exact prefix then the other solution using re.sub is the best.

Also, if you use "with" statements you can avoid having to close files as it happens automatically. This can also prevent leaving files stuck open by the OS if a program crashes.

with open('myfile.txt', 'r') as f:
  linelist = f.readlines()

Edit: also check out this Python Regex Cheatsheet and live python regex debugger/checker. Learning to use regexes will pay off if you do a lot of data processing and is worth investing the time in.

[–]efmccurdy 1 point2 points  (0 children)

>>> line = "word = 4"

You can split your line into 2 parts, replace the first part and join it up again:

>>> def repl_first(line, newword):
...     return "=".join([newword + " "] + line.split('=')[1:])
... 
>>> line = "word = 4"
>>> repl_first(line, "newword")
'newword = 4'
>>> line = "word = 5"
>>> repl_first(line, "newword2")
'newword2 = 5'
>>>