SIGKILL 在一个简单的 python 脚本中添加列

SIGKILL adding column in a simple python script

我有一个包含单行 header 和一长列值的文件。我想添加第二列,其中包含从 10981(step = 1)开始直到文件末尾的值(当然省略 header)。问题是脚本需要大量内存,我的电脑崩溃了,可能是因为脚本制作不好(对不起,我是新编程!)。 我做的脚本是这样的:

with open ('chr1.phyloP46way.placental2.wigFix', 'w') as file_open:
    num = 10981
    text = file_open.readlines()
    next (text)
    for line in text:
        num = num + 1
        print line.strip() + '\t' + str(num)

由于我的 PC 在 运行 时崩溃,我尝试在 pycharm 中测试它并出现以下错误,我所看到的可能是由于内存不足:

Process finished with exit code 137 (interrupted by signal 9: SIGKILL)

有什么解决办法吗?

非常感谢!

如果没有 .txt 很难验证它是否工作,但试试那个

f = open(os.path.join(data_path, 'chr1.phyloP46way.placental2.wigFix'), 'r')
lines = f.readlines()
num = 10981

for line_num in range(len(lines)):

    line_in = lines[line_num]

    num = num + 1
    print line_in.strip() + '\t' + str(num)

---- 更新:遵循 Rory Daulton 评论

我有时间做了一个小测试。也许这会有所帮助: 将以下代码保存在名为 converter.py

的文件中
import os

def add_enumeration(data_path, filename_in, filename_out, num=10981):

    # compose the filenames:
    path_to_file_in  = os.path.join(data_path, filename_in)
    path_to_file_out = os.path.join(data_path, filename_out)

    # check if the input file exists: 
    if not os.path.isfile(path_to_file_in):
        raise IOError('Input file does not exists.')

    # open the files:
    # if f_out does not exists it will be created.
    # if f_out is not empty, content will be deleted
    f_in  = open(path_to_file_in, 'r')
    f_out = open(path_to_file_out, 'w+')  

    # write the first line of the file in:
    f_out.write(f_in.readline())

    for line_in in f_in:

        f_out.write(line_in.strip() + '    ' + str(num) + '\n')
        num = num + 1

    f_in.close()
    f_out.close()

然后从 ipython 终端:

In: run -i converter.py

In: add_enumeration('/Users/user/Desktop', 'test_in.txt', 'test_out.txt')

注意,如果test_out不为空,其内容将被删除。 这应该避免使用 readlines() 导入列表中的所有行。让我知道内存问题是否仍然存在。

如果您的系统 运行 资源不足,可能的罪魁祸首是 readlines() 调用,它导致 Python 尝试将整个文件加载到内存中。没有必要这样做......文件对象本身可以用作迭代器来逐行读取文件:

with open ('chr1.phyloP46way.placental2.wigFix', 'w') as file_open:
    num = 10981
    next (file_open)
    for line in file_open:
        num = num + 1
        print line.strip() + '\t' + str(num)