python中如何在写文件之前删除文件内容_如何在python中删除文件的一部分?

I have a file named a.txt which looks like this:

I'm the first line

I'm the second line.

There may be more lines here.

I'm below an empty line.

I'm a line.

More lines here.

Now, I want to remove the contents above the empty line(including the empty line itself).

How could I do this in a Pythonic way?

解决方案

Basically you can't delete stuff from the beginning of a file, so you will have to write to a new file.

I think the pythonic way looks like this:

# get a iterator over the lines in the file:

with open("input.txt", 'rt') as lines:

# while the line is not empty drop it

for line in lines:

if not line.strip():

break

# now lines is at the point after the first paragraph

# so write out everything from here

with open("output.txt", 'wt') as out:

out.writelines(lines)

Here are some simpler versions of this, without with for older Python versions:

lines = open("input.txt", 'rt')

for line in lines:

if not line.strip():

break

open("output.txt", 'wt').writelines(lines)

and a very straight forward version that simply splits the file at the empty line:

# first, read everything from the old file

text = open("input.txt", 'rt').read()

# split it at the first empty line ("\n\n")

first, rest = text.split('\n\n',1)

# make a new file and write the rest

open("output.txt", 'wt').write(rest)

Note that this can be pretty fragile, for example windows often uses \r\n as a single linebreak, so a empty line would be \r\n\r\n instead. But often you know the format of the file uses one kind of linebreaks only, so this could be fine.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值