我希望一次读取一行,并将该字符串赋给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
也许有更好的解决办法。根据我对你问题的理解,这对我很有效。在执行过程中,每一行都被分配给变量
keyword
。这就是我用print keyword
来阐述这个事实的原因。此外,为了演示,我使用了time.sleep(5)
。在这5秒钟的暂停期间,您可以检查您的txt文件,它将包含您希望的数据(当第二行指定给变量时,第一行将从txt文件中删除)。你知道吗代码:
试试这个,让我知道你进展如何。需要注意的是,在处理文件对象时,Pythonic方法是使用
with open
语法,因为这样可以确保在离开缩进代码块后关闭文件。:)相关问题 更多 >
编程相关推荐