我试图创建一个只在python中读取/打印某一行的程序。到目前为止,我有这个:
import random
import time
a = open("settings.txt", "r")
b = open("settings.txt", "a")
adding = input("Enter Name: ")
with open("settings.txt", "a") as f:
f.write("\n{}".format(adding))
data = [line.rstrip() for line in a.readlines()]
print(", ".join(data))
time.sleep(10)
在我的settings.txt中:
Blah 1
Blah 2
Blah 3
我如何只打印程序(例如)Blah 1而不是该txt文件的其他内容?
答案 0 :(得分:3)
以下为您打开文件,打印第一行,然后关闭它:
with open("settings.txt", "r") as f:
print f.readline()
答案 1 :(得分:2)
如果只是第一行,你可以这样做:
for line in open('afile.txt'):
print line
break
如果它是您想要的随机行,您可以这样做:
from random import choice
print choice(list(open('afile.txt')))