繁体   English   中英

从文本文件python写入文本文件

[英]write text file from text files python

我有3个输出文件,分别包含x,y,z坐标

file1.txt(仅包含x)| file2(Y)| 文件3(Z)

2.113
3.023
-7.234
...

还有一个父pdb文件,其中包含坐标数据。 我只想从pdb文件中提取那些与file1,file2,file3中的x,y,z坐标匹配的行。

原子1 O5'GA 93 -12.706 19.299 0.129 1.00 0.00 O

粗体值将是我匹配整个行的匹配条件。

1-我如何将三个输出文件合并成一个文件,该文件可以在一行中给我x,y,z坐标以与我的脚本一起工作。

final_file = [文件1,文件2,文件3]?

2-如何根据匹配条件提取点;

def read_convex_points(final_file,parent_pdb):
    with open("output.txt","w") as f1:
        with open(final_file) as f2:
            with open(parent_pdb) as f3:
                for line1 in f2:
                    for line2 in f3: 
                        if line1 in line2:
                            f1.write(line2)
    return               

final_file = "file1.txt"
parent_pdb = "original.pdb"
read_convex_points(final_file,parent_pdb)

我写了类似的函数,但是如果条件不起作用。

您可以像这样合并文件:

def merge(paths):
    with open(paths[0]) as f1, open(paths[1]) as f2, open(paths[2]) as f3:
        try:
            yield next(f1), next(f2), next(f3)
        except StopIteration:
            return

for x, y, z in merge((file1, file2, file3)):
    # check if matching

需要注意的是,这是假设文件的长度相等,因此一旦遇到最短的文件,它将停止。 这可能是可以接受的。

这是在Python中将多个文件粘贴在一起的一种方法。 它可以处理任意数量的输入文件,但是与Peter的解决方案一样,如果文件具有不同的行数,则在最短的文件用完时它会停止。

输出文件中的字段由delimiter字符串delimiter ,默认情况下为空格。

def paste(sources, dest, delimiter=' '):
    fsrc = [open(fname, 'r') for fname in sources]
    fdest = open(dest, 'w')
    for t in zip(*fsrc):
        outline = delimiter.join([line.strip() for line in t]) + '\n'
        fdest.write(outline)
    for f in fsrc:
        f.close()
    fdest.close()


paste(('file1', 'file2', 'file3'), 'final_file')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM