如何在读取文本文件的内容时写入文本文件的中间? [英] How do I write to the middle of a text file while reading its contents?

查看:38
本文介绍了如何在读取文本文件的内容时写入文本文件的中间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先感谢您帮助我移动文件并帮助我处理 tcl 脚本.

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

我对 python 代码有一点疑问..如下..

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+] 

        puts $filelid 

        close $filelid 
"  

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("
")
            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...

示例:说.. 我将文件从程序文件复制到 sanity 文件夹,并在复制的文件之一中搜索词CloseAllOutputFile".找到单词后,应在该位置插入文本而不是文件末尾.

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.

推荐答案

在文件中间添加数据的一个简单方法是使用 fileinput 模块:

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

来自 fileinput 文档:

From the fileinput docs:

可选的就地过滤:如果关键字参数 inplace=1 是传递给 fileinput.input() 或 FileInput 构造函数,文件被移动到备份文件,标准输出被定向到输入文件(如果与备份文件同名的文件已经存在,则它将被默默替换).这使得编写过滤器成为可能重写它的输入文件到位.如果备份参数是给定(通常为 backup='.'),它指定备份文件的扩展名,备份文件仍然存在;经过默认情况下,扩展名是.bak",输出时将其删除文件已关闭.

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.

在不使用fileinput的情况下在读取数据的同时将数据插入filename文件:

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)

这篇关于如何在读取文本文件的内容时写入文本文件的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆