删除和更新Python文本文件中的行

2024-03-29 10:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,作为一个学习项目,我正在开发一个twitter机器人。我用的是python3。我在tweet中使用以下行。你知道吗

What is Bruce Lee’s favorite drink? Wataaaaah!
The dyslexic devil worshipper sold his soul to Santa.
You kill vegetarian vampires with a steak to the heart.
There was a prison break and I saw a midget climb up the fence. As he jumped down he sneered at me and I thought, well that’s a little condescending.

这是我使用Twython发tweet的代码:

from twython import Twython, TwythonError
import time

APP_KEY = '##########'  # Customer Key here
APP_SECRET = '#############'  # Customer secret here
OAUTH_TOKEN = '###############'  # Access Token here
OAUTH_TOKEN_SECRET = '################'  # Access Token Secret here

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    with open('jokes.txt', 'r+') as file:
        buff = file.readlines()

    for line in buff:
        if len(line)<140:
            print ("Tweeting...")
            twitter.update_status(status=line)
            time.sleep(3)
            with open ('jokes.txt', 'r+') as file:
                buff.remove(line)
                file.writelines(buff)
        else:
            with open ('jokes.txt', 'r+') as file:
                buff.remove(line)
                file.writelines(buff)
            print ("Skipped line - Char Length Violation")
            continue


except TwythonError as e:
    print (e)

我想跳过控制台上消息中超过140个字符的行Skipped line - Char Length Violation,然后删除该行并更新文件。脚本通过忽略该行成功发送tweet,但无法打印控制台消息。它也无法从文本文件中删除该行。你知道吗

我不知道为什么第三行You kill vegetarian vampires with a steak to the heart.被跳过了。你知道吗

我的代码有什么问题,为什么在运行脚本后文本文件看起来像这样:

The dyslexic devil worshipper sold his soul to Santa.
There was a prison break and I saw a midget climb up the fence. As he jumped down he sneered at me and I thought, well that’s a little condescending.d at me and I thought, well that’s a little condescending.nd I thought, well that’s a little condescending.


Tags: andthetoappthatherewithline
2条回答

首先,尽量避免使用file来命名变量,因为它是Python中用于类型file的保留关键字。你知道吗

固定代码:

from twython import Twython, TwythonError
import time

APP_KEY = '##########'  # Customer Key here
APP_SECRET = '#############'  # Customer secret here
OAUTH_TOKEN = '###############'  # Access Token here
OAUTH_TOKEN_SECRET = '################'  # Access Token Secret here

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    with open('jokes.txt', 'r+') as fp:
        buff = fp.readlines()

    for line in buff[:]:
        if len(line) < 140:
            print("Tweeting...")
            twitter.update_status(status=line)
            time.sleep(3)
            with open('jokes.txt', 'w') as fp:
                buff.remove(line)
                fp.writelines(buff)
        else:
            with open('jokes.txt', 'w') as fp:
                buff.remove(line)
                fp.writelines(buff)
            print("Skipped line - Char Length Violation")
            continue


except TwythonError as e:
    print(e)

通常-就像在本例中-在循环内修改iterable(列表)不是一个好主意,循环对同一iterable进行迭代。这里的技巧是第for line in buff[:]:行中的切片操作符,它生成buff列表的副本,并在副本上而不是在原始的buff列表上迭代。你知道吗

另外,如果要覆盖文件,必须以“w”模式打开,而不是以“r+”模式打开,因为“r+”不会首先截断文件。你知道吗

file.close()

似乎在with ... as file:块下放错了位置。with的优点是你不需要做这种记账。你知道吗

else块中,file对象是关闭的,因此file.writelines()应该引发异常。你知道吗

据我所知,buff是一个字符串,因此是不可变的。您可能想尝试buff = buff.remove(...),但它甚至有remove方法吗?你知道吗

相关问题 更多 >