问题描述
首先感谢您帮助我移动文件并帮助我处理 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
的情况下在读取数据的同时将数据插入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)
这篇关于如何在读取文本文件的内容时写入文本文件的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!