如何在 Python 中更改文件的第一行? [英] How to Change First Line of File in Python?

查看:98
本文介绍了如何在 Python 中更改文件的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does Python-2.7 on Windows truncate a file? The problem is well known with shutil.copyfile but I don't understand how to avoid it when I'm changing the first line. File size is unknown and could be huge.

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

Reference below but I'd prefer better exception handling with something like the following code:

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)

参考:在 python 中更改文件的第一行

推荐答案

您需要将文件的新版本创建为 NamedTemporaryFile.构建完成后,在旧文件的顶部重命名它.

You need to create the new version of the file as a NamedTemporaryFile. After you finish constructing it, you then rename it on top of the old file.

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

之后:

/testcode/file2
"-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

这篇关于如何在 Python 中更改文件的第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆