我试图弄清楚如何将一个文本块从一个文件移动到另一个文件中的特定点。我有大量如下所示的文件:
H -9.92247800 1.33807800 -0.69208300
S -9.74392800 0.01073000 -0.55448800
C -7.98603700 0.04294200 -0.19355700
C -7.45325900 -1.23715800 0.02112600
...
我想将数字列移动到之前看起来像这样的文件中:
...
0 1 0 1 0 1
H 0 H
S 0 H
C 0 H
C 0 H
...
所以应该喜欢这样:
...
0 1 0 1 0 1
H 0 -9.92247800 1.33807800 -0.69208300 H
S 0 -9.74392800 0.01073000 -0.55448800 H
C 0 -7.98603700 0.04294200 -0.19355700 H
C 0 -7.45325900 -1.23715800 0.02112600 H
...
有没有办法对大量文件自动执行此操作?我知道我可以选择一个块,复制它,然后手动将其粘贴到另一个文件中,但我有太多文件,因此这是不可行的。
数字块始终在同一位置(行和列)开始和结束,并且我要粘贴到的位置始终位于同一行和列。
答案1
不知道你是否愿意使用 Python,并且可能有一种使用不同语言的简洁方法,但 Python 可以通过以下方式做到这一点:
代码:
# describe where the text block is located
f1_start = 2, 18
f1_size = 4, 40
f2_start = 4, 19
# open all three files
with open('file1', 'rU') as f1, open('file2', 'rU') as f2, open('file3', 'w') as f3:
# skip some lines in file1
for _ in range(f1_start[0] - 1):
f1.readline()
# write first block of file2 to file3
for _ in range(f2_start[0] - 1):
f3.write(f2.readline())
# read from and merge lines in file1 and file 2
for _ in range(f1_size[0]):
l1 = f1.readline()[f1_start[1]:f1_start[1] + f1_size[1]].rstrip()
l2 = f2.readline()
l3 = l2[:f2_start[1]] + l1 + l2[f2_start[1]:]
f3.write(l3)
# write remaining lines from file2 to file3
while True:
l2 = f2.read()
if not l2:
break
f3.write(l2)
结果:
...
0 1 0 1 0 1
H 0 -9.92247800 1.33807800 -0.69208300 H
S 0 -9.74392800 0.01073000 -0.55448800 H
C 0 -7.98603700 0.04294200 -0.19355700 H
C 0 -7.45325900 -1.23715800 0.02112600 H
...