How to Overwrite Part of a Text File in Python

how do i overwrite to a specific part of a text file in python

You can use fileinput

import fileinput

with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(textToSearch, textToReplace), end='')
#testToSearch:- Daniel
#textToReplace:- newName

Or if you want to keep it more simple, just do the operation in reading from 1 file and writing the replaced content in a second file. And then overrite it!

f1 = open('orgFile.txt', 'r')
f2 = open('orgFileRep.txt', 'w')
for line in f1:
f2.write(line.replace('textToSearch', 'textToReplace'), end=' ')
f1.close()
f2.close()

Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:

import re

myfile = "path/test.xml"

with open(myfile, "r+") as f:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
f.truncate()

The other way is to read the file then open it again with open(myfile, 'w'):

with open(myfile, "r") as f:
data = f.read()

with open(myfile, "w") as f:
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))

Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).

By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html

Overwrite text file but not from The start

One solution is to just read the first two lines and write them again. Then write the new lines after that.

overwriting a specific line in a txt file

Your first approach was already near the solution, but there you are not selecting the 1st or 3rd line, you are just creating a list containing a 1 (lines = [1]. You first need to open the file. Then, you can use file.readlines which returns a list containing each line as one separate string, instead of file.read, which returns the whole file as one string. Then, you assign a new value to one specific line, open the same file again, but now in write mode, use file.writelines to write the list of lines back to the file, and that's it !

if answer == "R":
print("Racer")
with open("character.txt", "r") as f: # with automatically closes the file - no need to do so yourself
lines = f.readlines()

amount = input("please enter the amount") # no need to convert the amount to int first if you then convert it back to string below
lines[0] = answer + "-" + amount
with open("character.txt", "w") as f:
f.writelines(lines)

I will let you adapt the code for the other answers yourself. Please note that you could save many lines of code if you would put the above in a function hat accepts a number (the line you want to overwrite) and a string (the answer).

You surely wondered why I put lines[0] = ... in the code. Well, we start counting from 1, but Python starts counting from 0 ! What you call the 1st line, is for Python the 0st, what you call the 2nd, is for Python the 1st. and so on.

And here some notes to your second approach: file.seek seeks to the byte in the file specified by the number you passed to it, not to the line. And file.truncate resizes the file. It does not overwrite the file.

Replace a certain part of a text in a line - python

It looks like, already after reading the first line, it jumps at the end of the fileto write, and after that there is no other line. Mine is not the most elegant solution, but it works:

map_dict = {"variable_1": "20", "variable_2": "15"}
handle = open("filename.wbjn", "r+")
processed = []
for l in handle:
for k, v in map_dict.items():
l = l.replace(k, str(v))
processed.append(l)
handle.seek(0)
handle.write("".join(processed))
handle.truncate()
handle.close()

Python process and overwrite external text file

You need to open temp file and read from file, remove old file and rename to new name

import os
import numpy as np
import math
import cv2 as cv

#path = '/media/D/code/OCR/text-detection-ctpn/data/mlt_english+chinese/image'
gt_file = '12.txt'
output = open("temp.txt","w")
with open(gt_file, 'r') as f:
for line in f:
line = line.replace("[", "")
line = line.replace("(", "")
line = line.replace(")", "")
line = line.replace("]", "")
line = line.replace(" ", "")

output.write(line)
output.close()
os.remove(gt_file) # remove old file
os.rename("temp.txt",gt_file) # rename as old file

Read and overwrite a file in Python

If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

The functionality will likely also be cleaner and safer using open as a context manager, which will close the file handler, even if an error occurs!

with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()


Related Topics



Leave a reply



Submit