我如何使用python写入大型txt文件的每个字符?

问题描述 投票:0回答:1

我正在尝试使程序通过whatsapp网络发送文本文件的每个字符,但是该文件太大,因此当程序制作大字符串时,由于内存错误而崩溃。

这是我的代码:

from pynput.keyboard import Key, Controller
import time
import random
pi = open('pi.txt').read()
keyboard = Controller()
input("Press enter to continue")
cont = 5
while cont > 0 :
    time.sleep(1)
    print(cont)
    cont -= 1

for x in pi:
    tic = random.randint(0,10)/10
    time.sleep(tic)
    keyboard.type(x)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)

随机时间是指whatsapp不会将我检测为机器人

python memory pi
1个回答
1
投票

您可以尝试使用以下代码:

from pynput.keyboard import Key, Controller
import time
import random
keyboard = Controller()
input("Press enter to continue")
cont = 5
while cont > 0 :
    time.sleep(1)
    print(cont)
    cont -= 1

with open('pi.txt') as pi:

    for x in pi:
        tic = random.randint(0,10)/10
        time.sleep(tic)
        keyboard.type(x)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

说明:当您使用“ read”方法时,实际上会将文件中的所有文本读入pi变量。

在上面的代码中,您可以看到迭代是逐行进行的。

内部文件是按块延迟地进行迭代的,因此整个文件永远不会完全存在于内存中,因此不会导致崩溃。

© www.soinside.com 2019 - 2024. All rights reserved.