在python 3.5.1中编辑特定行

2024-04-29 15:21:35 发布

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

在python3.5.1中重写特定行有困难,我知道有一些解决方案,但是它们使用外部模块,或者是冗长的,并且特定于这个问题

有没有一行代码可以做到这一点? 下面是我要找的:File.write(“在这里插入文本”,“要覆盖的行”)

这是我的密码:

from time import sleep
import os
#functions
def pause():
    pause = input("Paused press <ENTER> to continue")
print("attempting to open workspace......")
#

Fo = open("work1.txt", 'r+')#opens the file
print("workspace opened")
#mainloop :D
def Mainloop():
    global Fo
    Fo.close()
    Fo = open("work1.txt", 'r+')
    os.system('cls')
    print('''

''')
    print ("   ======")
    print ("   Read")
    print ("   Write")
    print ("   ======")
    print("")
    INP = input('   >')
    if INP == "Read":
        Hm = input("how much?")
        print("")
        if Hm == 'All':
            print(Fo.read())
        else:
            print(Fo.read(int(Hm)))
        sleep(2)
        pause()
        os.system('cls')
        Mainloop()
    if INP == "Write":
        TextToAdd = input("Text to Write:   ")
        Fo.write(TextToAdd)
        os.system('cls')
        Mainloop()
    else:
        print('Not avaliable')
        sleep(2)
        os.system('cls')
        Mainloop()

Mainloop()
pause()

Tags: toinputifossleepopensystemwrite
1条回答
网友
1楼 · 发布于 2024-04-29 15:21:35

要用另一行替换文本文件中的一行吗

    for line in open(filename):
        if line.rstrip('\n') == search_pattern:
            sys.stdout.write('%s\n' % replacement)
        else:
            sys.stdout.write('%s' % line)

代替sys.stdout.write(),您可以填充一个列表,或者写入一个(临时)文件,等等

重要的思想是首先获得所需的输入(搜索模式、替换字符串),然后逐行遍历文件

解决方案属性:

  • 内存使用率低(因为您只在内存中保留一行)
  • O(n)runtime—文件的行数越多,此方法所需的时间就越长

或者,如果保证文件很小,可以将内容读入字符串,并使用str.replace()替换正在搜索的行

相关问题 更多 >