gpt4 book ai didi

python - 如何在读取文件内容时写入文本文件的中间部分?

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:32 26 4
gpt4 key购买 nike

首先感谢您帮助我移动文件并帮助我使用 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)

这段用于将文件从一个位置复制到另一个位置、在特定文件中搜索关键字并将数据写入文件的代码正在运行...

我怀疑每当我写..它写到文件末尾而不是当前位置...

示例:说.. 我将文件从程序文件复制到 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

来自 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.

在不使用 fileinput 的情况下将数据插入到 filename 文件中:

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)

关于python - 如何在读取文件内容时写入文本文件的中间部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16556944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com