我试图将包含多行的特定文本粘贴到D:\ output文件夹中包含的所有.txt文件中
我用这些代码列出了存储在输出文件夹下的所有.txt文件;
import os
myDir = 'D:\output'
# r=root, d=directories, f = files
for r, d, f in os.walk(myDir):
for file in f:
if ".txt" in file:
print(os.path.join(r, file))
每个.txt文件都有一个如下所示的部分。我想将我的文字块放在下面。
!**********************************************************************
! Global parameters
!**********************************************************************
.
.
.
这是我的多行文本块
searchpath (1) = '.'
gravity (1) = 0.0000000000000000E+00 ! Gravity
gravity (2) = 0.0000000000000000E+00 ! Gravity
gravity (3) = -9.8100000000000005E+00 ! Gravity
vehicle.startvel= 0.0000000000000000E+00 ! Vehicle initial velocity
vehicle.applystartvel= 0! Apply vehicle initial velocity at solver start
最后,我要使所有这些文件
!**********************************************************************
! Global parameters
!**********************************************************************
searchpath (1) = '.'
gravity (1) = 0.0000000000000000E+00 ! Gravity
gravity (2) = 0.0000000000000000E+00 ! Gravity
gravity (3) = -9.8100000000000005E+00 ! Gravity
vehicle.startvel= 0.0000000000000000E+00 ! Vehicle initial velocity
vehicle.applystartvel= 0! Apply vehicle initial velocity at solver start
.
.
.
有人可以帮助我如何使用python吗?我是新手。
答案 0 :(得分:1)
没有简单的方法来编辑文本文件并在中间添加数据,因为它们是顺序的非索引文件。
常见的方法是创建一个新的临时文件,然后以所需的方式重写整个txt,然后删除原始文件并重命名新文件以替换旧文件。
以下示例未经测试,请备份您的数据。
text_to_find = '''\
!**********************************************************************
! Global parameters
!**********************************************************************
'''
block_to_add = '''\
searchpath (1) = '.'
gravity (1) = 0.0000000000000000E+00 ! Gravity
gravity (2) = 0.0000000000000000E+00 ! Gravity
gravity (3) = -9.8100000000000005E+00 ! Gravity
vehicle.startvel= 0.0000000000000000E+00 ! Vehicle initial velocity
vehicle.applystartvel= 0! Apply vehicle initial velocity at solver start
'''
import os
myDir = r'D:\output'
for path, dirs, files in os.walk(myDir):
for filename in files:
if filename.endswith('.txt'):
fullname = os.path.join(path, filename)
with open(fullname) as f:
data = f.read() # read the entire file to memory
pos = data.find(text_to_find) #locate the text
if pos != -1: # found, insert the block
pos += len(text_to_find)
data = data[:pos] + block_to_add + data[pos:]
with open(fullname, 'w') as f:
f.write(data) # rewrite the entire file