从文本文件中读取行并在每次运行脚本时删除它们

2024-09-28 23:52:03 发布

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

我希望一次读取一行,并将该字符串赋给Python脚本中的一个变量。一旦分配了这个值,我想从txt文件中删除这一行。刚才我有下一个代码:

import os

# Open file with a bunch of keywords
inputkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r')

# Assigning
keyword = inputkeywordsfile.readline().strip()

例如,如果.txt文件具有以下结构:

dog
cat
horse

我第一次运行我的脚本,狗将被分配到关键字。 第二次运行脚本时,cat将被指定为关键字,dog将从文本文件中删除。你知道吗

已解决:

readkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r')
firstline = readkeywordsfile.readline().strip()
lines = readkeywordsfile.readlines()
readkeywordsfile.close()

del lines[0:1]

writekeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w')
writekeywordsfile.writelines(lines)
writekeywordsfile.close()

keyword = firstline

Tags: 文件pathtxt脚本readlineosopenkeyword
2条回答

也许有更好的解决办法。根据我对你问题的理解,这对我很有效。在执行过程中,每一行都被分配给变量keyword。这就是我用print keyword来阐述这个事实的原因。此外,为了演示,我使用了time.sleep(5)。在这5秒钟的暂停期间,您可以检查您的txt文件,它将包含您希望的数据(当第二行指定给变量时,第一行将从txt文件中删除)。你知道吗

代码

import os
import time

f = open("KeywordDatabase.txt","r")
lines = f.readlines()
f.close()
k = 0
for line in lines:
    if k == 0:
        keyword = line #Assignment takes place here
        print keyword
        f = open("KeywordDatabase.txt","w")
        for w in lines[k:]:
            f.write(w)
        k += 1
        f.close()
    else:
        keyword = line #Assignment takes place here
        print keyword
        f = open("KeywordDatabase.txt","w")
        for w in lines[k:]:
            f.write(w)
        f.close()
        k += 1
    time.sleep(5) #Time to check the txt file :)

试试这个,让我知道你进展如何。需要注意的是,在处理文件对象时,Pythonic方法是使用with open语法,因为这样可以确保在离开缩进代码块后关闭文件。:)

import os

# Open file with a bunch of keywords
with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') as inputkeywordsfile:

    # Read all lines into a list and retain the first one
    keywords = inputkeywordsfile.readlines()
    keyword = keywords[0].strip()

with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w') as outputkeywordsfile:
    for w in keywords[1:]:
        outputkeywordsfile.write(w)

相关问题 更多 >