首页 > 编程知识 正文

如何使用python删除一个文件,python强制删除文件夹

时间:2023-05-05 04:39:22 阅读:45092 作者:4060

基本上不能从文件开头删除东西,必须写入新文件。

我觉得pythonic方式看起来是这样的:

# getaiteratoroverthelinesinthefile :

withopen(input.txt,) rt ) ) as lines:

# while the line is not empty drop it

for line in lines:

if not line.strip () :

布雷克

# nowlinesisatthepointafterthefirstparagraph

# so write out everything from here

withopen(output.txt,) wt ) ) as out:

out.writelines(lines )或更低版本是简单的版本,旧版本的Python没有with。

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

for line in lines:

if not line.strip () :

布雷克

open('output.txt ',' wt ' ).writelines(lines )和非常简单的版本,只需在空行中拆分文件。

# first,read everything from the old file

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

# splititatthefirstemptyline ('nn ' ) )。

first,rest=text.split('nn ',1 ) )。

# make a new文件and write the rest

open(output.txt ),wt ).write(rest )请注意,这可能非常脆弱。 例如,Windows通常将rn用作单个换行符,因此空行将更改为rnrn。 但是,这可能没有问题,因为我们知道文件格式通常只使用一种换行符。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。