【问题标题】:How to read a txt file in a .py file and then place the 2nd line of the txt file in the specified position?如何读取 .py 文件中的 txt 文件,然后将 txt 文件的第 2 行放在指定位置?
【发布时间】:2021-09-10 16:38:49
【问题描述】:

我希望 saved.txt 文件中第 2 行中的数字始终位于此位置 K().type('022543 ') 数字后有一个空格很重要.

保存的.txt

some kind of link
022543

加载.py

import time
import os
import webbrowser
from pynput.keyboard import Key, Controller as K

from itertools import islice
with open('saved.txt') as fin:
    for line in islice(fin, 1, 16):
        print(line)

os.startfile("c:\Program Files\Kodi\kodi.exe")
time.sleep(4)
K().type('022543 ')

示例 2。

saved.txt
some kind of link
1849

load.py
K().type('1849 ')

提前感谢您的帮助!

【问题讨论】:

    标签: python python-3.x import pynput


    【解决方案1】:

    要获取代表第二行的字符串 - 您可以从文件中读取所有行

    file = open("saved.txt")
    lines = file.readlines()
    

    然后使用lines[2] 访问第2 行。 否则,您可以使用 linecache 模块。 见:https://www.codespeedy.com/read-a-specific-line-from-a-text-file-in-python/

    之后就是字符串拼接,在末尾加一个空格。

    【讨论】:

    • 不幸的是,我不知道这些数字是怎么来的K().type('1849 ')
    • 感谢我解决了 txt 文件中的空间问题,它更容易,但如何将它放到正确的位置我还没有解决
    • 你有字符串吗?像我们上面讨论的line = lines[2]?如果是这样,您可以使用K.type(line + ' ') 吗?除非我误解了这个问题......
    • 我搞砸了……现在可以了。非常感谢您的帮助! import time import os import webbrowser from pynput.keyboard import Key, Controller as K file = open("saved.txt") lines = file.readlines() line = lines[1] os.startfile("c:\Program Files\Kodi\kodi.exe") time.sleep(2) K().type(line + ' ')
    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2016-06-18
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多