M
M
micsma2021-08-13 20:16:02
Python
micsma, 2021-08-13 20:16:02

How to replace a line in a file using python?

With this code, I can output line 3:

with open('1.txt') as f:
  line = f.readlines()[2]
print(line)


Content 1.txt:
11
33
name
password


I need to replace only 3 lines in file 1.txt

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2021-08-13
@micsma

Let's say this:

with open('your_file.txt', 'r') as file:
    data = file.readlines()

print(data)

data[2] = '@micsma\n'
with open('your_file.txt', 'w') as file:
    file.writelines(data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question