在文本文件中的字符之间写入?

时间:2014-11-02 02:19:33

标签: python-2.7 fwrite

我有一个我想写的模块。我有几个问题。其中一个在文件中定位一个字符串。目前我打开文件,然后在(文件名)中使用for行,然后执行if以确定它是否找到字符串,并且所有这些都有效。然而之前(它现在被注释掉)我试图确定它在使用tell()时的位置。然而这给了我一个不正确的位置,我认为1118而不是660。所以我手动确定了使用搜索的位置。

然而,第二个问题是,如果我在文件中的位置写入此文件,它只会覆盖其上的所有数据。我想插入数据而不是覆盖它。

除非我插入一个字符长度相等的字符串,我希望写入发生,否则它将覆盖大多数if语句和类似下面的内容。

有没有办法天真地做到这一点?

这是我要写入的文件

# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
#   if specified to do so

import os
import maya.cmds as mc
import module_locator

my_path = module_locator.module_path()

def usercurve_lib(fbxfile=None, remove=None):
    """All control/curve objects created by user

    Keyword Arguments:
    fbxfile -- (string) name of fbx file to import
    remove -- (boolean) will remove an entry from the library and delete the
        associated fbx file
    """
    curves_dict = {
    #crvstart

    #crvend
    }
    if remove is None:
        return curves_dict
    elif not remove:
        try:
            name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
                iv=True, pmt=False)
            return name[0]
        except RuntimeError:
            return None
    else:
        try:
            os.remove('%s\%s.fbx' %(my_path, fbxfile))
            return '%s.fbx' %(fbxfile)
        except OSError:
            print 'File %s does not exist.' %(fbxfile)
            return None

这是下面的代码,我在一个名为neo_curves.py的模块中运行(这不是完整的代码,'my_path'只是当前目录的路径neo_curves.py正在运行)

def create_entry(self, crv):    

    """Exports user curve to user data directory and adds entry into
        neo_usercurves.py

        Keyword Arguments:
        crv -- (PyNode) the object to export
        """
        # set settings
        mel.eval('FBXExportFileVersion "FBX201400"')
        mel.eval('FBXExportInputConnections -v 0')
        select(crv)
        mc.file('%s\userdat\%s.fbx' %(my_path, str(crv)), force=True, options='',
            typ='FBX export', pr=True, es=True)
        with open('%s\userdat\\neo_usercurves.py' %(my_path), 'r+') as usercrvs:
            for line in usercrvs:
                if line.strip() == '#crvstart':
                    #linepos = usercrvs.tell()
                    #linepos = int(linepos)
                    #usercrvs.seek(linepos, 0)
                    usercrvs.seek(665, 0)
                    usercrvs.write("\n    "+str(crv)+" : '%s\%s' %(my_path, '"+
                       str(crv)+".fbx')")
                    break

这将给我以下结果:

# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
#   if specified to do so

import os
import maya.cmds as mc
import module_locator

my_path = module_locator.module_path()

def usercurve_lib(fbxfile=None, remove=None):
    """All control/curve objects created by user

    Keyword Arguments:
    fbxfile -- (string) name of fbx file to import
    remove -- (boolean) will remove an entry from the library and delete the
        associated fbx file
    """
    curves_dict = {
    #crvstart
    loop_crv : '%s\%s' %(my_path, 'loop_crv.fbx')     return curves_dict
    elif not remove:
        try:
            name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
                iv=True, pmt=False)
            return name[0]
        except RuntimeError:
            return None
    else:
        try:
            os.remove('%s\%s.fbx' %(my_path, fbxfile))
            return '%s.fbx' %(fbxfile)
        except OSError:
            print 'File %s does not exist.' %(fbxfile)
            return None

1 个答案:

答案 0 :(得分:0)

简而言之:在大多数操作系统上,如果长度不同,则无法在不重写的情况下插入文件。

在这里查看一个长时间的讨论:Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)