Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python replace line in file

# You can't read and write to a file at the same time so you first need to read
# the contents of the file, save it and then reopen the file after changing the
# values to write the updates to the file. NOTE: when writing to a file it rewrites
# the entire file. This is why saving the original contents of the file is important.
file = []
with open('hello_world.txt', 'r') as f:
    file = f.readlines()

with open('hello_world.txt', 'w') as f:
    file[2] = "This is actually not a test file"
    f.write("".join(file))
 
PREVIOUS NEXT
Tagged: #python #replace #line #file
ADD COMMENT
Topic
Name
8+2 =