Skip to main content
 首页 » 编程设计

python之在 Python 中合并文件

2025年05月04日22bjzhanghao

我想合并 2 个文件。第一个文件 (co60.txt) 仅包含整数值,第二个文件 (bins.txt) 包含 float 。

co60.txt:

11 
14 
12 
14 
18 
15 
18 
9 

bins.txt:

0.00017777777777777795 
0.0003555555555555559 
0.0005333333333333338 
0.0007111111111111118 
0.0008888888888888898 
0.0010666666666666676 
0.0012444444444444456 
0.0014222222222222236 

当我用这段代码合并这两个文件时:

with open("co60.txt", 'r') as a: 
    a1 = [re.findall(r"[\w']+", line) for line in a] 
with open("bins.txt", 'r') as b: 
    b1 = [re.findall(r"[\w']+", line) for line in b] 
with open("spectrum.txt", 'w') as c: 
    for x,y in zip(a1,b1): 
        c.write("{} {}\n".format(" ".join(x),y[0])) 

我得到:

11 0 
14 0 
12 0 
14 0 
18 0 
15 0 
18 0 
9 0 

看来,当我合并这 2 个文件时,此代码仅合并文件 bins.txt 的舍入值。

如何让文件像这样合并:

11 0.00017777777777777795 
14 0.0003555555555555559 
12 0.0005333333333333338 
14 0.0007111111111111118 
18 0.0008888888888888898 
15 0.0010666666666666676 
18 0.0012444444444444456 
9 0.0014222222222222236 

请您参考如下方法:

你可以不用正则表达式::

with open("co60.txt") as a, open("bins.txt") as b, \ 
    open("spectrum.txt", 'w') as c: 
    for x,y in zip(a, b): 
        c.write("{} {}\n".format(x.strip(), y.strip())) 

spectrum.txt 的内容:

11 0.00017777777777777795 
14 0.0003555555555555559 
12 0.0005333333333333338 
14 0.0007111111111111118 
18 0.0008888888888888898 
15 0.0010666666666666676 
18 0.0012444444444444456 
9 0.0014222222222222236