[英]Merging files in Python
I want to merge 2 files. 我想合并2个文件。 First file (
co60.txt
) contains only integer values and the second file ( bins.txt
) contains float numbers. 第一个文件(
co60.txt
)仅包含整数值,第二个文件( bins.txt
)包含浮点数。
co60.txt: co60.txt:
11
14
12
14
18
15
18
9
bins.txt: bins.txt:
0.00017777777777777795
0.0003555555555555559
0.0005333333333333338
0.0007111111111111118
0.0008888888888888898
0.0010666666666666676
0.0012444444444444456
0.0014222222222222236
When I merge those two file with this code: 当我使用以下代码合并这两个文件时:
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]))
I get: 我得到:
11 0
14 0
12 0
14 0
18 0
15 0
18 0
9 0
It appears that when I merge these 2 files, this code only merges round values of the file bins.txt
. 似乎当我合并这两个文件时,此代码仅合并文件
bins.txt
舍入值。
How do I get that files merge like this: 我如何使文件像这样合并:
11 0.00017777777777777795
14 0.0003555555555555559
12 0.0005333333333333338
14 0.0007111111111111118
18 0.0008888888888888898
15 0.0010666666666666676
18 0.0012444444444444456
9 0.0014222222222222236
You can do it without regex:: 您可以不使用正则表达式:
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()))
Content of spectrum.txt
: 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
如@immortal所述,如果要使用正则表达式,请使用-
b1 = [re.findall(r"[0-9\.]+", line) for line in b]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.