-1

Sorry for posting such an easy question, but i couldn't find an answer on google. I wish my code to do something like this code:

lines = open("Bal.txt").write
lines[1] = new_value
lines.close()

p.s i wish to replace the line in a file with a value

Mathew Wright
  • 15
  • 1
  • 7
  • 1
    When you say replace a line by _its_ column, are you referring to some arbitrary character-column in a file, or some column based on a certain delimiter, or something else? It would be helpful to get some clarification on that point to be able to give a useful answer to your question. As for the replacing a line part, here's a thread explaining that sub-question: https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python. I can't fit the code snippet in a comment, but essentially, you need to replace the line of the file, then re-write the whole file. – mediantis Oct 05 '16 at 13:00
  • By column, i mean its position in the file. where lines[1] would be the first line located in the text file – Mathew Wright Oct 05 '16 at 13:06
  • Apologies for what would seem like a silly question to you as I haven't quite caught on - in your code snippet, is new_value simply any arbitrary text from somewhere else that you want to be the new text for row 1 in your 'Bal.txt'? – mediantis Oct 05 '16 at 13:12
  • new_value is a variable – Mathew Wright Oct 05 '16 at 13:20
  • If new_value is a string I think the above link may apply: `with open('Bal.txt', 'r') as file: data = file.readlines(); data[1] = new_value with open('Bal.txt', 'w') as file: file.writelines( data )` (Can't format code snippets in comments unfortunately) – mediantis Oct 05 '16 at 13:29
  • Do you mean row as opposed to column? – Kapocsi Oct 05 '16 at 13:36

1 Answers1

0

xxx.dat before:

ddddddddddddddddd
EEEEEEEEEEEEEEEEE
fffffffffffffffff

with open('xxx.txt','r') as f:
    x=f.readlines()
x[1] = "QQQQQQQQQQQQQQQQQQQ\n"
with open('xxx.txt','w') as f:
    f.writelines(x)

xxx.dat after:

ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQ
fffffffffffffffff

Note:f.read() returns a string, whereas f.readlines() returns a list, enabling you to replace an occurrence within that list.
Inclusion of the \n (Linux) newline character is important to separate line[1] from line[2] when you next read the file, or you would end up with:

ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQfffffffffffffffff
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60