Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write to the middle of a text file while reading its contents?

Tags:

python

file-io

First of all thanks for helping me out with moving files and for helping me in with tcl script.

Small doubt i had with python code.. as below..

import os
import shutil

data =" set filelid [open \"C:/Sanity_Automation/Work_Project/Output/smokeTestResult\" w+] \n\
        puts $filelid \n\
        close $filelid \n"  

path = "C:\\Sanity_Automation\\RouterTester900SystemTest"
if os.path.exists(path):
    shutil.rmtree('C:\\Sanity_Automation\\RouterTester900SystemTest\\')

path = "C:\\Program Files (x86)"
if os.path.exists(path):
    src= "C:\\Program Files (x86)\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
else:
    src= "C:\\Program Files\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
dest = "C:\\Sanity_Automation\\RouterTester900SystemTest\\"

shutil.copytree(src, dest)
log = open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl','r+')
log_read=log.readlines()
x="CloseAllOutputFile"
with open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl', 'a+') as fout:
        for line in log_read:
          if x in line:
            fout.seek(0,1)
            fout.write("\n")
            fout.write(data)

This code for copying files from one location to another, searching keyword in particular file and writing data to file is working...

My doubt is whenever i write.. It writes to end of file instead of current location...

Example: Say.. I copied file from program files to sanity folder and searched for word "CloseAllOutputFile" in one of the copied file. when the word found, it should insert text in that position instead of end of file.

like image 443
Yashwanth Nataraj Avatar asked Oct 20 '25 11:10

Yashwanth Nataraj


2 Answers

A simple way to add data in the middle of a file is to use fileinput module:

import fileinput

for line in fileinput.input(r'C:\Sanity_Automation\....tcl', inplace=1):
    print line, # preserve old content
    if x in line:
       print data # insert new data

From the fileinput docs:

Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed.

To insert data into filename file while reading it without using fileinput:

import os
from tempfile import NamedTemporaryFile

dirpath = os.path.dirname(filename)
with open(filename) as file, \
     NamedTemporaryFile("w", dir=dirpath, delete=False) as outfile:
    for line in file:
        print >>outfile, line, # copy old content
        if x in line:
           print >>outfile, data # insert new data

os.remove(filename) # rename() doesn't overwrite on Windows
os.rename(outfile.name, filename)
like image 117
jfs Avatar answered Oct 23 '25 00:10

jfs


you dont all you can do is read in the file, insert the text you want, and write it back out

with open("some_file","r") as f:
     data = f.read()
some_index_you_want_to_insert_at = 122
some_text_to_insert = "anything goes here"

new_data = data[:some_index_you_want_to_insert_at] + some_text_to_insert + data[some_index_you_want_to_insert_at:]

with open("some_file","w") as f:
     f.write(new_data)

print "all done!"
like image 35
Joran Beasley Avatar answered Oct 23 '25 01:10

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!