Python - 打开txt文件,删除每一行的最后一位数字并覆盖旧文件 [英] Python - open txt file, remove last digits of every line and overwrite old file

查看:43
本文介绍了Python - 打开txt文件,删除每一行的最后一位数字并覆盖旧文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 有没有办法读入 txt 文件,删除每行的最后 6 个字符,然后用相同的内容覆盖旧文件,只是没有每行的最后 6 个字符?

Is there a way in Python to read in a txt file, remove the last 6 characters of each line and overwrite the old file with the same content just without the last 6 chars on each line?

我尝试过这样的事情:

with open(dat, "r+") as fp:
    for line in fp:
        line = line[:-6]
        fp.write(line+"\n")

但这只会给我一个奇怪的文件,在错误的地方有多个条目和数字.

But that only gives me a weird looking file with multiple entries and numbers at the wrong places.

还有

with open(dat, "r+") as fp:
    for line in fp:
        line = line[:-6]
        fp.write(line+"\n")

不起作用.当我这样做时,整个文件都是空的.

doesn't work. The whole file is empty when I am doing that.

是否有一种聪明的方法可以在不进行更改的情况下将所有内容写入单独的文件?

Is there a smart way of doing this without doing the change, writing everything to a seperate file?

推荐答案

你需要将改变的字符追加到一个临时列表中,然后将文件指针移回开头再写入:

You need to append the changed characters to a temporary list and then move the file pointer back to the beginning before writing again:

with open(dat, "r+") as fp:
    temp_list = []
    for line in fp:
        line = line[:-6]
        temp_list.append(line)
    fp.seek(0, 0)
    fp.write("\n".join(temp_list))

希望能帮到你

这篇关于Python - 打开txt文件,删除每一行的最后一位数字并覆盖旧文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆