简体   繁体   中英

write text file from text files python

I have 3 output files containing x, y, z coordinates respectively

file1.txt (contains x only) | file2 (Y) | file3 (Z)

2.113
3.023
-7.234
...

and a parent pdb file which contains coordinates data. I want to extract only those lines from pdb file matching with x,y,z coordinates from file1,file2,file3.The pdb file lines are;

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

The bold values would be my matching criteria to copy the whole line.

1- How I can merge the three output files to make a single file which can give me x,y,z coordinates in a line to work with my script.

final_file = [file1, file2, file3] ?

2- How I can extract points on matching criteria;

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)

I wrote function something like that but if condition is not working.

You can merge files like this:

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

The caveat is this assumes files are of equal length, so it will stop the moment it encounters shortest file. This is probably accetable.

Here's one way to paste together multiple files in Python. It handles any number of input files, but like Peter's solution if the files have different numbers of lines it stops when the shortest file runs out of lines.

Fields in the output file are separated by the delimiter string, which is a space by default.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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