简体   繁体   English

如何仅从txt文件打印一行? (蟒蛇)

[英]How to only print one line from a txt file? (python)

Im trying to create a program which only reads/prints a certain line in python. 我试图创建一个只读取/打印python中特定行的程序。 So far i have got this: 到目前为止,我已经知道了:

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)

In my settings.txt: 在我的settings.txt中:

Blah 1 
Blah 2
Blah 3

How do I only get the program to print (for example) Blah 1 and nothing else from that txt file? 如何仅使程序打印(例如)Blah 1,而从该txt文件中打印其他内容?

The following opens up the file for you, prints the first line, and then closes it: 以下内容为您打开文件,打印第一行,然后关闭它:

with open("settings.txt", "r") as f:
    print f.readline()

If it is just the first line, you could do: 如果仅是第一行,则可以执行以下操作:

for line in open('afile.txt'):
    print line
    break

If it is a random line that you want, you could do: 如果您想要的是一条随机线,则可以执行以下操作:

from random import choice
print choice(list(open('afile.txt')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM