求代码 如何删除文件中的行,windows环境

xieshen947 2017-03-15 12:01:25
我只找到了linux的环境,请问有windows环境可以用的吗


我想删除其中三行,第一行 第二行和最后一行
...全文
198 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
屎克螂 2017-03-16
  • 打赏
  • 举报
回复
引用 4 楼 xieshen947 的回复:
引用 1 楼 uiuiy1 的回复:
百度 python读写文件
百度有用的话我就不废话了
我的意思是让你自己动手去玩,这是最基础的东西。

dList = open('C:/Users/sa/Desktop/a.txt').readlines()
dList.pop(-1)
dList.pop(1)
dList.pop(0)
with open('C:/Users/sa/Desktop/b.txt', 'wb') as f:
    f.writelines(dList)
xieshen947 2017-03-16
  • 打赏
  • 举报
回复
引用 6 楼 uiuiy1 的回复:
引用 4 楼 xieshen947 的回复:
[quote=引用 1 楼 uiuiy1 的回复:] 百度 python读写文件
百度有用的话我就不废话了
我的意思是让你自己动手去玩,这是最基础的东西。

dList = open('C:/Users/sa/Desktop/a.txt').readlines()
dList.pop(-1)
dList.pop(1)
dList.pop(0)
with open('C:/Users/sa/Desktop/b.txt', 'wb') as f:
    f.writelines(dList)
[/quote]文件小还可以,文件大呢
sprawling 2017-03-16
  • 打赏
  • 举报
回复
如果在linux下面,这个是连python都用不上的,直接sed搞定了 windows下面,如果有unix-like环境,也可以用sed的
John_Me 2017-03-15
  • 打赏
  • 举报
回复

# -*- coding: utf-8 -*
import time
import os

#要操作的文件名
file_name = 'file_name'
tmp_file_name = '{}.{}'.format(file_name, int(time.time()))
with open(tmp_file_name, 'wb') as f_write:
    with open(file_name, 'rb') as f_read:
        tmp_line = ''
        for idx, line in enumerate(f_read):
            # 去掉第一行, 第二行
            if idx in [0, 1]:
                continue

            # 迟写一行,既可以删除最后行
            if idx > 2:
                f_write.write(tmp_line)
            tmp_line = line


os.remove(file_name)
os.rename(tmp_file_name, file_name)


屎克螂 2017-03-15
  • 打赏
  • 举报
回复
百度 python读写文件
xieshen947 2017-03-15
  • 打赏
  • 举报
回复
引用 1 楼 uiuiy1 的回复:
百度 python读写文件
百度有用的话我就不废话了
xieshen947 2017-03-15
  • 打赏
  • 举报
回复
引用 2 楼 jon_me 的回复:

# -*- coding: utf-8 -*
import time
import os

#要操作的文件名
file_name = 'file_name'
tmp_file_name = '{}.{}'.format(file_name, int(time.time()))
with open(tmp_file_name, 'wb') as f_write:
    with open(file_name, 'rb') as f_read:
        tmp_line = ''
        for idx, line in enumerate(f_read):
            # 去掉第一行, 第二行
            if idx in [0, 1]:
                continue

            # 迟写一行,既可以删除最后行
            if idx > 2:
                f_write.write(tmp_line)
            tmp_line = line


os.remove(file_name)
os.rename(tmp_file_name, file_name)


谢谢

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧