首先感谢帮助我移动文件和帮助我使用tcl脚本.
小疑问我有python代码..如下所示..
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)
Run Code Online (Sandbox Code Playgroud)
此代码用于将文件从一个位置复制到另一个位置,在特定文件中搜索关键字并将数据写入文件正在运行...
我的疑问是每当我写的..它写到文件末尾而不是当前位置...
示例:说..我将文件从程序文件复制到sanity文件夹,并在其中一个复制文件中搜索单词"CloseAllOutputFile".当找到单词时,它应该在该位置插入文本而不是文件末尾.
在文件中间添加数据的简单方法是使用fileinput模块:
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
Run Code Online (Sandbox Code Playgroud)
可选的就地过滤:如果将关键字参数inplace = 1传递给fileinput.input()或FileInput构造函数,则将文件移动到备份文件,并将标准输出定向到输入文件(如果是文件的与备份文件相同的名称已经存在,它将被静默替换).这使得编写一个可以重写其输入文件的过滤器成为可能.如果给出了备份参数(通常为backup ='.'),则指定备份文件的扩展名,备份文件保留在周围; 默认情况下,扩展名为".bak",并在输出文件关闭时删除.
filename在读取数据时将数据插入文件而不使用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)
Run Code Online (Sandbox Code Playgroud)