简体   繁体   English

Python 读取文件并以另一种格式写入

[英]Python read file and write in another format

I am trying to read a txt-file with many values of pairs in two colmns (XY values) and I wand them to be writen in another txt-file with 4 pairs XY at each row (8 values per row).我正在尝试读取一个 txt 文件,其中包含两个列(XY 值)中的许多对值,我希望将它们写入另一个 txt 文件,每行有 4 对 XY(每行 8 个值)。

So, from that:所以,从那:

0,038043    0,74061
0,038045    0,73962
0,038047    0,73865
0,038048    0,73768
0,03805 0,73672
0,038052    0,73577
0,038053    0,73482
0,038055    0,73388
0,038057    0,73295
0,038058    0,73203
0,03806 0,73112
0,038062    0,73021
0,038064    0,72931
0,038065    0,72842
0,038067    0,72754
0,038069    0,72666

to that:对此:

    0,038043    0,74061 0,038045    0,73962 0,038047    0,73865 0,038048    0,73768 
0,03805 0,73672 0,038052    0,73577 0,038053    0,73482 0,038055    0,73388
    0,038057    0,73295 0,038058    0,73203 0,03806 0,73112 0,038062    0,73021
    0,038064    0,72931 0,038065    0,72842 0,038067    0,72754 0,038069    0,72666

I tried:我试过了:

import itertools
files = [1, 2 ,3 ,4, 5, 6, 7,
8, 9, 10, 11, 12, 13]
for k in files:
    print 'k =',k
    with open("deflag_G{k}.inp".format(k=k)) as f1:
       with open("deflag_G_{k}.inp".format(k=k),"w") as f2:
            f2.writelines(itertools.islice(f1, 4, None))
    f2.close()
    f1.close()

But I am not taking 4 pairs (8 values per line) in the new file.但是我没有在新文件中使用 4 对(每行 8 个值)。 Any help is appreciated.任何帮助表示赞赏。

One way to approach this is to spit the logic out.解决这个问题的一种方法是吐出逻辑。 First get the data to a list of XY, then chunk the data to rows of 8 XY and then save the data (ie write data to another text file)首先将数据获取到 XY 列表,然后将数据分块为 8 个 XY 行,然后保存数据(即将数据写入另一个文本文件)

The chunk method I've borrowed from another stack overflow answer.我从另一个堆栈溢出答案中借来的块方法。

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n] 

input = [
'0,038043, 0,74061',
'0,038045, 0,73962',
'0,038047, 0,73865',
'0,038048, 0,73768',
'0,03805,  0,73672',
'0,038052, 0,73577',
'0,038053, 0,73482',
'0,038055, 0,73388',
'0,038057,  0,73295',
'0,038058, 0,73203',
'0,03806, 0,73112',
'0,038062, 0,73021',
'0,038064, 0,72931',
'0,038065, 0,72842',
'0,038067, 0,72754',
'0,038069, 0,7266'
] # Convert data to list of X-Y    

for x in list(chunks(input, 8)): # 8 is the number of chunk
    print(x) # This contains an array of 8 X-Y (e.g ['0,038043, 0,74061', '0,038045, 0,73962', '0,038047, 0,73865', '0,038048, 0,73768', '0,03805, 0,73672', '0,038052, 0,73577', '0,038053, 0,73482', '0,038055, 0,73388'])

... you could add your logic to save data to csv.

If you have a generic batcher that will work on an iterable, you can use it directly on the file object to read lists of up to 4 lines.如果你有一个可以处理迭代的通用批处理器,你可以直接在文件 object 上使用它来读取最多 4 行的列表。 For example:例如:

def batcher(iterable, n):
    while True:
        vals = []
        for i in range(n):
            try:
                vals.append(next(iterable))
            except StopIteration:
                if vals:
                    yield vals
                return
        yield vals

with open("input.txt") as f1:
    with open("output.txt", "w") as f2:
        for lines in batcher(f1, 4):
            f2.write(' '.join((l.replace("\n", "") for l in lines)) + '\n')
import itertools
#i = 0
j = 0
for k in range (1,14):
    print 'k =',k
    with open("deflag_G{k}.inp".format(k=k)) as f1:
       with open("deflag_G_{k}.inp".format(k=k),"w") as f2:
            #lines = f1.readlines()
            for i, line in enumerate(f1):
                print i 
                j = j + 1
                print j
                b = line.split()[0]
                s = float(b)
                #print "b:", b
                d = line.split()[1]
                e = float(d)                
                if j == 8:
                   j = 0   
# ('%s'%s + ' , ' + '%e'%e + '\n')                   
                   f2.write(line.rstrip('\n') + ","+ '\n')
                else:                  
                    print(repr(line))               
            #if line.startswith(searchquery):
                    f2.write(line.rstrip('\n') + ",  " )
            #f2.write('%s'%listc + "\n")
               # i = i + 1
        #else :
        #    i = i+1
        #os.close(f1)
    f1.close()
    f2.close()

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

相关问题 Python从读取文件中拆分行,然后在另一文件中以另一种格式写入它们 - Python split lines from read file and write them with another format in another file 尝试读取FASTA格式的文件,然后写入Genbank格式的另一个文件 - Trying to read file in FASTA format and then write to another file in Genbank format Python:读取和写入复杂且重复格式的文件 - Python: Read and write the file of complex and reapeating format 如何使用特定的输出格式在python中将矩阵(从一个文件读取)写入另一个csv文件 - How to write a matrix (read from one file) to another csv file in python with a specific output format 从文件读取并写入另一个python - Read from file and write to another python python写入文件与matlab写入文件,由另一软件读取 - python write file vs matlab write file, read by another software 读取文件并写入另一个文件 - Read a file and Write on another Python:使用自定义格式读取CSV并写入文件 - Python: Read CSV and write to file using a custom format 读取tcp,应用数学运算,格式化字符串和写入文件的python脚本 - python script to read tcp, apply math, format string, and write file 从Excel读取数据并以CSV格式写入文件-Python - Read data from excel and write as CSV format to a file - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM