如何在Python中更改第一行文件?

时间:2018-02-11 08:21:32

标签: python python-2.7 shutil

为什么Windows上的Python-2.7会截断文件?这个问题在shutil.copyfile中众所周知,但是当我改变第一行时,我不明白如何避免它。文件大小未知,可能很大。

下面的参考,但我更喜欢使用以下代码更好的异常处理:

import os
import sys
import shutil

with open(sys.argv[1], 'r+') as src:
    line = src.readline()
    with open(sys.argv[1], 'r+') as dst:
        dst.write = sys.argv[1]+'\n'
        shutil.copyfileobj(src, dst)

参考:change first line of a file in python

1 个答案:

答案 0 :(得分:2)

您需要将文件的新版本创建为NamedTemporaryFile。完成构建后,然后将其重命名为旧文件。

代码:

$table->string('facebook_id')->unique()->nullable();

测试代码:

def insert_line_front(insert_filename, to_insert):

    with open(insert_filename) as src, tempfile.NamedTemporaryFile(
            'w', dir=os.path.dirname(insert_filename), delete=False) as dst:

        # Discard first line
        src.readline()

        # Save the new first line
        dst.write(to_insert + '\n')

        # Copy the rest of the file
        shutil.copyfileobj(src, dst)

    # remove old version
    os.unlink(insert_filename)

    # rename new version
    os.rename(dst.name, insert_filename)

    return()

之前:

import os
import shutil
import sys
import tempfile

# For noob - Function code goes here

filename = os.path.abspath(sys.argv[1])
insert_line_front(filename, filename)

后:

/testcode/file1
"-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02"
"3.739478886127E-01","1.782759875059E-01","6.490543365479E+01"
"3.298096954823E-01","6.939357519150E-02","2.112392578125E+02"
"-2.319437451661E-02","1.149862855673E-01","2.712340698242E+0