gpt4 book ai didi

python - 在Python中修改文本文件中的每一行

转载 作者:行者123 更新时间:2023-12-01 02:33:03 26 4
gpt4 key购买 nike

我有一个大文件,如下例所示:

1   10161   10166   3
1 10166 10172 2
1 10172 10182 1
1 10183 10192 1
1 10193 10199 1
1 10212 10248 1
1 10260 10296 1
1 11169 11205 1
1 11336 11372 1
2 11564 11586 2
2 11586 11587 3
2 11587 11600 4
3 11600 11622 2

我想在每行的开头添加一个“chr”,例如:

chr1    10161   10166   3
chr1 10166 10172 2
chr1 10172 10182 1
chr1 10183 10192 1
chr1 10193 10199 1
chr1 10212 10248 1
chr1 10260 10296 1
chr1 11169 11205 1
chr1 11336 11372 1
chr2 11564 11586 2
chr2 11586 11587 3
chr2 11587 11600 4
chr3 11600 11622 2

我在 python 中尝试了以下代码:

   file = open("myfile.bg", "r")
for line in file:
newline = "chr" + line
out = open("outfile.bg", "w")
for new in newline:
out.write("n"+new)

但没有返回我想要的。您知道如何为此目的修复代码吗?

最佳答案

您的代码的问题是您迭代输入文件而不对您读取的数据执行任何操作:

file = open("myfile.bg", "r")
for line in file:
newline = "chr" + line

最后一行将 myfile.bg 中的每一行分配给 newline 变量(一个字符串,前面带有 'chr'),每个行覆盖先前的结果。

然后迭代 newline 中的字符串(这将是输入文件中的最后一行,前面带有 'chr'):

out = open("outfile.bg", "w")
for new in newline: # <== this iterates over a string, so `new` will be individual characters
out.write("n"+new) # this only writes 'n' before each character in newline

如果您只执行一次,例如在 shell 中,您可以使用单行代码:

open('outfile.bg', 'w').writelines(['chr' + line for line in open('myfile.bg').readlines()])

更正确的(尤其是在程序中,您会关心打开的文件句柄等)是:

with open('myfile.bg') as infp:
lines = infp.readlines()
with open('outfile.bg', 'w') as outfp:
outfp.writelines(['chr' + line for line in lines])

如果文件确实很大(接近可用内存的大小),您需要增量处理它:

with open('myfile.bg') as infp:
with open('outfile.bg', 'w') as outfp:
for line in infp:
outfp.write('chr' + line)

(尽管这比前两个版本慢得多..)

关于python - 在Python中修改文本文件中的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com