`
黑鸟酱
  • 浏览: 123405 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

python 文件插入第一行

 
阅读更多
def file_insert(fname,linenos=[],strings=[]):  
    """ 
    Insert several strings to lines with linenos repectively. 
 
    The elements in linenos must be in increasing order and len(strings) 
    must be equal to or less than len(linenos). 
 
    The extra lines ( if len(linenos)> len(strings)) will be inserted 
    with blank line. 
    """  
    if os.path.exists(fname):  
        lineno = 0  
        i = 0  
        for line in fileinput.input(fname,inplace=1):  
            # inplace must be set to 1  
            # it will redirect stdout to the input file  
            lineno += 1  
            line = line.strip()  
            if i<len(linenos) and linenos[i]==lineno:  
                if i>=len(strings):  
                    print "\n",line  
                else:  
                    print strings[i]  
                    print line  
                i += 1  
            else:  
                print line

 fileinput.input的inplace必须要设为1,以便让stdout被重定向到输入文件里:

file_insert('a.txt' ,[ 1 , 4 , 5 ],[ 'insert1' , 'insert4' ]

 

分享到:
评论
2 楼 miniduan 2013-06-21  
i here by provide one that works:

import os

def prepend(filename, data, bufsize=1<<15):
    # backup the file
    backupname = filename + os.extsep+'bak'
    try: os.unlink(backupname) # remove previous backup if it exists
    except OSError: pass
    os.rename(filename, backupname)

    # open input/output files,  note: outputfile's permissions lost
    with open(backupname) as inputfile, open(filename, 'w') as outputfile:
        # prepend
        outputfile.write(data)
        # copy the rest
        buf = inputfile.read(bufsize)
        while buf:
            outputfile.write(buf)
            buf = inputfile.read(bufsize)

    # remove backup on success
    try: os.unlink(backupname)
    except OSError: pass

print 'austin test'
prepend('D:\\aduan\\program\\abc.txt','i love her\n')
print 'austin test done'


output:
D:\aduan\program>type abc.txt
i love youi love you
D:\aduan\program>type abc.txt
i love youi love you
D:\aduan\program>python python.insert1stLine.py
austin test
austin test done

D:\aduan\program>type abc.txt
i love her
1 楼 miniduan 2013-06-21  
验证了一下,不好用啊:

import fileinput, os

def file_insert(fname,linenumbers=[],strings=[]): 
    """
    Insert several strings to lines with linenumbers repectively.

    The elements in linenumbers must be in increasing order and len(strings)
    must be equal to or less than len(linenumbers).

    The extra lines ( if len(linenumbers)> len(strings)) will be inserted
    with blank line.
    """ 
    if os.path.exists(fname): 
        lineno = 0 
        i = 0 
        for line in fileinput.input(fname,inplace=1): 
            # inplace must be set to 1 
            # it will redirect stdout to the input file 
            lineno += 1 
            line = line.strip() 
            if i<len(linenumbers) and linenumbers[i]==lineno: 
                if i>=len(strings): 
                    print "\n",line 
                else: 
                    print strings[i] 
                    print line 
                i += 1 
            else: 
                print line

print 'austin test'
file_insert('D:\\aduan\\program\\abc.txt', [1,4,5], ['i love you'])
print 'austin test done'

相关推荐

    python 实现在txt指定行追加文本的方法

    lines.insert(1, 'a new line') # 在第二行插入 s = '\n'.join(lines) fp = file&#40;'data.txt', 'w'&#41; fp.write(s) fp.close() 以上这篇python 实现在txt指定行追加文本的方法就是小编分享给大家的全部内容了,...

    Python办公自动化视频.rar

    ├第1章 Python基础从零到1 │ │ 1.10高级语法_类和对象.mp4 │ │ 1.11高级语法_模块.mp4 │ │ 1.1基本语法_输出函数print_变量与赋值.mp4 │ │ 1.2基本语法_数据类型.mp4 │ │ 1.3基本语法_输入函数input.mp4 ...

    Python实现的插入排序算法原理与用法实例分析

    插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后...

    Python操作word文档插入图片和表格的实例演示

    图片是Word的一种特殊内容,这篇文章主要介绍了关于Python操作word文档,向里面插入图片和表格的相关内容,下面话不多说了,来一起看看详细的代码 实例代码: # -*- coding: UTF8 -*- from docx import Document ...

    Python实现文件复制删除

     这个是我的第一个python小程序。  下面就来看其代码的实现。 首先插入必要的库: import os import os.path import shutil import time, datetime 然后就是一大堆功能函数。第一个就是把某一目录下的所有文件...

    Python复制文件操作实例详解

    这个是我的第一个python小程序。 下面就来看其代码的实现。 首先插入必要的库: import os import os.path import shutil import time, datetime 然后就是一大堆功能函数。第一个就是把某一目录下的所有文件

    Python数据可视化(处理地下车库情况的CSV文件,统计信息并绘图)

    3、从第一步得到的TXT文本文件中再次读取数据,并计算某两列的商,将结果再导入到一个EXCEL表格文件中; 4、打开第三步得到的Excel文件,使用其中的某列数据进行分组,求均值,并以柱状图展示; 5、使用某列数据进行...

    python cookbook(第3版)

    第一章:数据结构和算法 1.1 解压序列赋值给多个变量 1.2 解压可迭代对象赋值给多个变量 1.3 保留最后N个元素 1.4 查找最大或最小的N个元素 1.5 实现一个优先级队列 1.6 字典中的键映射多个值 1.7 字典排序 ...

    python常用快捷键

    #新建工程第一步操作 1. module设置把空包分层去掉,compact empty middle package 2. 设置当前的工程是utf-8,设置的Editor--&gt;File Encodings--&gt;全部改成utf-8, #注释 1. ctrl+/:单行注释 #光标操作 1. ...

    Python-Web自测试卷1.docx

    Python-Web自测试卷1全文共1页,当前为第1页。Python-Web自测试卷1全文共1页,当前为第1页。自测试卷1 Python-Web自测试卷1全文共1页,当前为第1页。 Python-Web自测试卷1全文共1页,当前为第1页。 一、选择题 1....

    read-big-file-with-python:案例研究的第一部分:使用python读取大型(21GB)文本文件

    用python读取大文件本来是第一个三部分案例研究(至今已扩展为5个部分)的第一部分是使用C,Python,PYSPARK,Spark-Scala和Athena / Glue读取大型(21GB)文本文件。 您可以在这里看到其他部分:这部分处理使用C和...

    atom-python-debugger:适用于Atom的类似IDE的Python调试器

    打开Python文件进行调试并插入断点 按alt-r显示调试器视图 如果适用,在输入参数字段中插入输入参数 点击Run按钮。 焦点移到第一个断点。 使用提供的按钮浏览源。 您可以直接在命令字段中输入调试器命令。 当前...

    python制作ppt源码和文件,可以通过编程完成,实现自动办公,高效率完成工作

    python制作ppt,可以通过编程完成,实现自动办公,高效率完成工作,本讲座一共分为四讲。...1.第一讲——了解11种默认布局 2.第二讲——插入文字的两种方法和追加文字 3.第三讲——插入文本框 4.第四讲——插入图片

    python-project-template:Python 项目的模板。 在此处插入标语。:trade_mark:

    这是 Python 项目模板的 README 文件。 作者: 克里斯·沃里克 &lt; &gt; 版权: :copyright: 2013-2021,克里斯·沃里克。 日期: 2021-01-01 版本: 2.3.1 内容 你的第一次提交 如果你准备好发布你的第一个...

    steal-all-files:Python脚本可使用USB设备自动窃取计算机中的所有文件和信息。 仅出于教育目的而创建

    格式化USB 我们要做的第一件事是格式化USB设备,为此,您可以连接它,然后在Windows和大多数Unix系统中right click &gt; format 。 如果使用Unix,并且想从终端格式化它,则可以使用: # Locate the usb device that ...

    基于python的接口自动化测试框架+源代码+文档说明

    * 调用被测试系统提供的接口,先数据驱动读取excel用例一行数据; * 发送请求数据,根据传参数据,向数据库查询得到对应的数据; * 将查询的结果组装成JSON格式的数据,同时根据返回的数据值与Excel的值对比判断,并...

    功能超级强悍的文本编辑器 PilotEdit 14.3.0 + x64 中文多语免费版.zip

    通过这个功能,我们可以很方便地找出第一个文件中存在而第二个文件中不存在的行 11. 自定义字符串表 &gt;单击即可添加一个自定义的字符串 &gt;在所选文本的前后分别添加自定义的字符串 12. 正则表达式 &gt;用正则表达式查找/...

    Python模块搜索概念介绍及模块安装方法介绍

    和C中的#include不同,Python中的import语句并不是简单的把一个文件插入另外一个文件。 导入其实是运行时的运算,程序第一次导入指定文件时,会执行以下步骤, 1. 找到模块文件 2. 编译成位码 3. 执行模块中的代码来...

    最新Python3.5零基础+高级+完整项目(28周全)培训视频学习资料

    第一个python程序 变量 字符编码与二进制 字符编码的区别与介绍 用户交互程序 if else流程判断 while 循环 while 循环优化版本 for 循环及作业要求 第2周 本节鸡汤 模块初识 pyc是什么 python数据类型 bytes数据...

    PythonTestST3:Sublime Text 3软件包,用于运行python单元测试

    此第一个发行版仅附带对eye2的内置支持。 输出颜色基于的主题和语言文件 安装 可以使用程序包控制或手动安装此插件。 要手动安装,请将此存储库克隆到sublime软件包目录中。 用法 PythonTest运行python测试,并在...

Global site tag (gtag.js) - Google Analytics